diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml index c6f6f3745c0..d1d812cbadb 100644 --- a/.github/workflows/samples-kotlin.yaml +++ b/.github/workflows/samples-kotlin.yaml @@ -30,8 +30,7 @@ jobs: #- samples/client/petstore/kotlin-json-request-string - samples/client/petstore/kotlin-jvm-okhttp4-coroutines - samples/client/petstore/kotlin-moshi-codegen - # need some special setup - #- samples/client/petstore/kotlin-multiplatform + - samples/client/petstore/kotlin-multiplatform - samples/client/petstore/kotlin-nonpublic - samples/client/petstore/kotlin-nullable - samples/client/petstore/kotlin-okhttp3 diff --git a/README.md b/README.md index 8aca24c1a67..210de6791d2 100644 --- a/README.md +++ b/README.md @@ -223,21 +223,21 @@ Examples: # Execute latest released openapi-generator-cli openapi-generator-cli version -# Execute version 3.1.0 for the current invocation, regardless of the latest released version -OPENAPI_GENERATOR_VERSION=3.1.0 openapi-generator-cli version +# Execute version 4.1.0 for the current invocation, regardless of the latest released version +OPENAPI_GENERATOR_VERSION=4.1.0 openapi-generator-cli version -# Execute version 3.1.0-SNAPSHOT for the current invocation -OPENAPI_GENERATOR_VERSION=3.1.0-SNAPSHOT openapi-generator-cli version +# Execute version 4.1.0-SNAPSHOT for the current invocation +OPENAPI_GENERATOR_VERSION=4.1.0-SNAPSHOT openapi-generator-cli version -# Execute version 3.0.2 for every invocation in the current shell session -export OPENAPI_GENERATOR_VERSION=3.0.2 -openapi-generator-cli version # is 3.0.2 -openapi-generator-cli version # is also 3.0.2 +# Execute version 4.0.2 for every invocation in the current shell session +export OPENAPI_GENERATOR_VERSION=4.0.2 +openapi-generator-cli version # is 4.0.2 +openapi-generator-cli version # is also 4.0.2 # To "install" a specific version, set the variable in .bashrc/.bash_profile -echo "export OPENAPI_GENERATOR_VERSION=3.0.2" >> ~/.bashrc +echo "export OPENAPI_GENERATOR_VERSION=4.0.2" >> ~/.bashrc source ~/.bashrc -openapi-generator-cli version # is always 3.0.2, unless any of the above overrides are done ad hoc +openapi-generator-cli version # is always 4.0.2, unless any of the above overrides are done ad hoc ``` ### [1.4 - Build Projects](#table-of-contents) @@ -844,6 +844,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2021-10-02 - [How to Write Fewer Lines of Code with the OpenAPI Generator](https://hackernoon.com/how-to-write-fewer-lines-of-code-with-the-openapi-generator) by [Mikhail Alfa](https://hackernoon.com/u/alphamikle) - 2021-10-12 - [OpenAPI Generator : 4000 étoiles sur GitHub et des spaghettis](https://www.youtube.com/watch?v=9hEsNBSqTFk) by [Jérémie Bresson](https://github.com/jmini) at [Devoxx FR 2021](https://cfp.devoxx.fr/2021/speaker/jeremie_bresson) - 2021-10-17 - [Generate a TypeScript HTTP Client From An OpenAPI Spec In DotNET 5](https://richardwillis.info/blog/generate-a-type-script-http-client-from-an-open-api-spec-in-dot-net-5) by [Richard Willis](https://github.com/badsyntax) +- 2021-11-06 - [スタートアップの開発で意識したこと](https://zenn.dev/woo_noo/articles/5cb09f8e2899ae782ad1) by [woo-noo](https://zenn.dev/woo_noo) +- 2021-11-09 - [Effective Software Development using OpenAPI Generator](https://apexlabs.ai/post/effective-software-development-using-openapi-generator) by Ajil Oomme ## [6 - About Us](#table-of-contents) @@ -1060,7 +1062,7 @@ If you want to join the committee, please kindly apply by sending an email to te | GraphQL | @renepardon (2018/12) | | Groovy | | | Haskell | | -| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @nmuesch (2021/01) | +| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) | | JMeter | @kannkyo (2021/01) | | Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) @andrewemery (2019/10) @4brunu (2019/11) @yutaka0m (2020/03) | | Lua | @daurnimator (2017/08) | diff --git a/bin/configs/swift5-frozenEnums.yaml b/bin/configs/swift5-frozenEnums.yaml new file mode 100644 index 00000000000..64dc04a4f81 --- /dev/null +++ b/bin/configs/swift5-frozenEnums.yaml @@ -0,0 +1,12 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/frozenEnums +inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + sortParamsByRequiredFlag: false + generateFrozenEnums: false + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator diff --git a/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml b/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml new file mode 100644 index 00000000000..22284f92f6c --- /dev/null +++ b/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml @@ -0,0 +1,11 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 13.0.1 + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-angular-petstore' + npmRepository: https://skimdb.npmjs.com/registry + snapshot: false + supportsES6: true diff --git a/bin/configs/typescript-angular-v13-provided-in-root.yaml b/bin/configs/typescript-angular-v13-provided-in-root.yaml new file mode 100644 index 00000000000..bf16e022ded --- /dev/null +++ b/bin/configs/typescript-angular-v13-provided-in-root.yaml @@ -0,0 +1,7 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 13.0.1 + supportsES6: true diff --git a/docs/generators.md b/docs/generators.md index ed80e860e49..8d8433cd23f 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -86,6 +86,7 @@ The following generators are available: * [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) +* [csharp-netcore-functions](generators/csharp-netcore-functions.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) * [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md) diff --git a/docs/generators/csharp-netcore-functions.md b/docs/generators/csharp-netcore-functions.md new file mode 100644 index 00000000000..50ec49b34a1 --- /dev/null +++ b/docs/generators/csharp-netcore-functions.md @@ -0,0 +1,300 @@ +--- +title: Config Options for csharp-netcore-functions +sidebar_label: csharp-netcore-functions +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false| +|conditionalSerialization|Serialize only those properties which are initialized by user, accepted values are true or false, default value is false.| |false| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I| +|library|HTTP library template (sub-template) to use|
**httpclient**
HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Experimental. May subject to breaking changes without further notice.)
**restsharp**
RestSharp (https://github.com/restsharp/RestSharp)
|restsharp| +|licenseId|The identifier of the license| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase| +|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false| +|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false| +|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| +|optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true| +|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false| +|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true| +|optionalProjectFile|Generate {PackageName}.csproj.| |true| +|packageGuid|The GUID that will be associated with the C# project| |null| +|packageName|C# package name (convention: Title.Case).| |Org.OpenAPITools| +|packageTags|Tags to identify the package| |null| +|packageVersion|C# package version.| |1.0.0| +|releaseNote|Release note, default to 'Minor update'.| |Minor update| +|returnICollection|Return ICollection<T> instead of the concrete type.| |false| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |src| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp2.0**
.NET Core 2.0 compatible
**netcoreapp2.1**
.NET Core 2.1 compatible
**netcoreapp3.0**
.NET Core 3.0 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
|netstandard2.0| +|useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| +|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| +|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| +|validatable|Generates self-validatable models.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|List| +|list|List| +|map|Dictionary| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✓|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index e74a239be25..9404a2fd458 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -11,6 +11,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|generateFrozenEnums|Generate frozen enums (default: true)| |true| |generateModelAdditionalProperties|Generate model additional properties (default: true)| |true| |hashableModels|Make hashable models (default: true)| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index ab8b3da35fc..2083b09cadf 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.ts).| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| -|ngVersion|The version of Angular. (At least 6.0.0)| |12.2.12| +|ngVersion|The version of Angular. (At least 6.0.0)| |13.0.1| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index ef348bbb266..83413a9ee11 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -29,7 +29,8 @@ public class CodegenOperation { isArray, isMultipart, isResponseBinary = false, isResponseFile = false, hasReference = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false; + isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false, + hasErrorResponseObject; // if 4xx, 5xx repsonses have at least one error object defined public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse; public CodegenDiscriminator discriminator; @@ -297,6 +298,7 @@ public class CodegenOperation { sb.append(", isResponseFile=").append(isResponseFile); sb.append(", hasReference=").append(hasReference); sb.append(", hasDefaultResponse=").append(hasDefaultResponse); + sb.append(", hasErrorResponseObject=").append(hasErrorResponseObject); sb.append(", isRestfulIndex=").append(isRestfulIndex); sb.append(", isRestfulShow=").append(isRestfulShow); sb.append(", isRestfulCreate=").append(isRestfulCreate); @@ -371,6 +373,7 @@ public class CodegenOperation { isResponseFile == that.isResponseFile && hasReference == that.hasReference && hasDefaultResponse == that.hasDefaultResponse && + hasErrorResponseObject == that.hasErrorResponseObject && isRestfulIndex == that.isRestfulIndex && isRestfulShow == that.isRestfulShow && isRestfulCreate == that.isRestfulCreate && @@ -435,6 +438,7 @@ public class CodegenOperation { produces, prioritizedContentTypes, servers, bodyParam, allParams, bodyParams, pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, optionalParams, authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs, vendorExtensions, - nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, operationIdSnakeCase); + nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, operationIdSnakeCase, + hasErrorResponseObject); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 046d8609d3c..e97a6caf557 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -570,14 +570,7 @@ public class DefaultCodegen implements CodegenConfig { List> models = (List>) inner.get("models"); for (Map mo : models) { CodegenModel cm = (CodegenModel) mo.get("model"); - for (CodegenProperty cp : cm.allVars) { - // detect self import - if (cp.dataType.equalsIgnoreCase(cm.classname) || - (cp.isContainer && cp.items != null && cp.items.dataType.equalsIgnoreCase(cm.classname))) { - cm.imports.remove(cm.classname); // remove self import - cp.isSelfReference = true; - } - } + removeSelfReferenceImports(cm); } } setCircularReferences(allModels); @@ -585,6 +578,23 @@ public class DefaultCodegen implements CodegenConfig { return objs; } + /** + * Removes imports from the model that points to itself + * Marks a self referencing property, if detected + * + * @param model Self imports will be removed from this model.imports collection + */ + protected void removeSelfReferenceImports(CodegenModel model) { + for (CodegenProperty cp : model.allVars) { + // detect self import + if (cp.dataType.equalsIgnoreCase(model.classname) || + (cp.isContainer && cp.items != null && cp.items.dataType.equalsIgnoreCase(model.classname))) { + model.imports.remove(model.classname); // remove self import + cp.isSelfReference = true; + } + } + } + public void setCircularReferences(Map models) { final Map> dependencyMap = models.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> getModelDependencies(entry.getValue()))); @@ -3966,6 +3976,12 @@ public class DefaultCodegen implements CodegenConfig { if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.is2xx) && Boolean.FALSE.equals(op.isResponseFile)) { op.isResponseFile = Boolean.TRUE; } + + // check if any 4xx or 5xx reponse has an error response object defined + if ((Boolean.TRUE.equals(r.is4xx) || Boolean.TRUE.equals(r.is5xx)) && + Boolean.FALSE.equals(r.primitiveType) && Boolean.FALSE.equals(r.simpleType)) { + op.hasErrorResponseObject = Boolean.TRUE; + } } op.responses.sort((a, b) -> { int aScore = a.isWildcard() ? 2 : a.isRange() ? 1 : 0; @@ -4259,6 +4275,7 @@ public class DefaultCodegen implements CodegenConfig { r.setComposedSchemas(getComposedSchemas(responseSchema)); if (ModelUtils.isArraySchema(responseSchema)) { r.simpleType = false; + r.isArray = true; r.containerType = cp.containerType; ArraySchema as = (ArraySchema) responseSchema; CodegenProperty items = fromProperty("response", getSchemaItems(as)); @@ -4314,6 +4331,8 @@ public class DefaultCodegen implements CodegenConfig { } else if (ModelUtils.isTypeObjectSchema(responseSchema)) { if (ModelUtils.isFreeFormObject(openAPI, responseSchema)) { r.isFreeFormObject = true; + } else { + r.isModel = true; } r.simpleType = false; r.containerType = cp.containerType; @@ -4325,9 +4344,6 @@ public class DefaultCodegen implements CodegenConfig { LOGGER.debug("Property type is not primitive: {}", cp.dataType); } - if (!r.isMap && !r.isArray) { - r.simpleType = true; - } r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); if (r.baseType == null) { @@ -4774,12 +4790,12 @@ public class DefaultCodegen implements CodegenConfig { final CodegenSecurity cs = defaultCodegenSecurity(key, securityScheme); cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isOAuth = false; cs.isBasic = true; - if ("basic".equals(securityScheme.getScheme())) { + if ("basic".equalsIgnoreCase(securityScheme.getScheme())) { cs.isBasicBasic = true; - } else if ("bearer".equals(securityScheme.getScheme())) { + } else if ("bearer".equalsIgnoreCase(securityScheme.getScheme())) { cs.isBasicBearer = true; cs.bearerFormat = securityScheme.getBearerFormat(); - } else if ("signature".equals(securityScheme.getScheme())) { + } else if ("signature".equalsIgnoreCase(securityScheme.getScheme())) { // HTTP signature as defined in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ // The registry of security schemes is maintained by IANA. // https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml @@ -5168,17 +5184,7 @@ public class DefaultCodegen implements CodegenConfig { cm.hasOnlyReadOnly = false; } - // TODO revise the logic to include map - if (cp.isContainer) { - addImport(cm, typeMapping.get("array")); - } - - addImport(cm, cp.baseType); - CodegenProperty innerCp = cp; - while (innerCp != null) { - addImport(cm, innerCp.complexType); - innerCp = innerCp.items; - } + addImportsForPropertyType(cm, cp); // if required, add to the list "requiredVars" if (Boolean.TRUE.equals(cp.required)) { @@ -5199,6 +5205,28 @@ public class DefaultCodegen implements CodegenConfig { return; } + /** + * For a given property, adds all needed imports to the model + * This includes a flat property type (e.g. property type: ReferencedModel) + * as well as container type (property type: array of ReferencedModel's) + * + * @param model The codegen representation of the OAS schema. + * @param property The codegen representation of the OAS schema's property. + */ + protected void addImportsForPropertyType(CodegenModel model, CodegenProperty property) { + // TODO revise the logic to include map + if (property.isContainer) { + addImport(model, typeMapping.get("array")); + } + + addImport(model, property.baseType); + CodegenProperty innerCp = property; + while (innerCp != null) { + addImport(model, innerCp.complexType); + innerCp = innerCp.items; + } + } + /** * Determine all of the types in the model definitions (schemas) that are aliases of * simple types. @@ -6558,6 +6586,10 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.pattern = toRegularExpression(schema.getPattern()); } + protected String toMediaTypeSchemaName(String contentType) { + return toModelName(contentType + "Schema"); + } + protected LinkedHashMap getContent(Content content, Set imports) { if (content == null) { return null; @@ -6605,9 +6637,9 @@ public class DefaultCodegen implements CodegenConfig { ceMap.put(propName, ce); } } - CodegenProperty schemaProp = fromProperty("schema", mt.getSchema()); - CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); String contentType = contentEntry.getKey(); + CodegenProperty schemaProp = fromProperty(toMediaTypeSchemaName(contentType), mt.getSchema()); + CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); cmtContent.put(contentType, codegenMt); } return cmtContent; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java index 86af0181b3d..75e466165a5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java @@ -505,7 +505,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { super.postProcessModelProperty(model, property); if (!model.isEnum && property.isEnum) { // These are inner enums, enums which do not exist as models, just as properties. - // They are handled via the enum_inline template and and are generated in the + // They are handled via the enum_inline template and are generated in the // same file as the containing class. To prevent name clashes the inline enum classes // are prefix with the classname of the containing class in the template. // Here the datatypeWithEnum template variable gets updated to match that scheme. @@ -529,9 +529,9 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); for (CodegenResponse r : op.responses) { - // By default only set types are automatically added to operation imports, not sure why. + // By default, only set types are automatically added to operation imports, not sure why. // Add all container type imports here, by default 'dart:core' imports are skipped - // but other sub classes may required specific container type imports. + // but other sub-classes may require specific container type imports. if (r.containerType != null && typeMapping().containsKey(r.containerType)) { final String value = typeMapping().get(r.containerType); if (needToImport(value)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java new file mode 100644 index 00000000000..8f189b444ba --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java @@ -0,0 +1,1151 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; +import io.swagger.v3.oas.models.media.Schema; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.ProcessUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; + +@SuppressWarnings("Duplicates") +public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { + // Defines the sdk option for targeted frameworks, which differs from targetFramework and targetFrameworkNuget + protected static final String MCS_NET_VERSION_KEY = "x-mcs-sdk"; + protected static final String SUPPORTS_UWP = "supportsUWP"; + protected static final String SUPPORTS_RETRY = "supportsRetry"; + + protected static final String NET_STANDARD = "netStandard"; + + // HTTP libraries + protected static final String RESTSHARP = "restsharp"; + protected static final String HTTPCLIENT = "httpclient"; + + // Project Variable, determined from target framework. Not intended to be user-settable. + protected static final String TARGET_FRAMEWORK_IDENTIFIER = "targetFrameworkIdentifier"; + // Project Variable, determined from target framework. Not intended to be user-settable. + protected static final String TARGET_FRAMEWORK_VERSION = "targetFrameworkVersion"; + + @SuppressWarnings("hiding") + private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + private static final List frameworkStrategies = Arrays.asList( + FrameworkStrategy.NETSTANDARD_1_3, + FrameworkStrategy.NETSTANDARD_1_4, + FrameworkStrategy.NETSTANDARD_1_5, + FrameworkStrategy.NETSTANDARD_1_6, + FrameworkStrategy.NETSTANDARD_2_0, + FrameworkStrategy.NETSTANDARD_2_1, + FrameworkStrategy.NETCOREAPP_2_0, + FrameworkStrategy.NETCOREAPP_2_1, + FrameworkStrategy.NETCOREAPP_3_0, + FrameworkStrategy.NETCOREAPP_3_1, + FrameworkStrategy.NETFRAMEWORK_4_7, + FrameworkStrategy.NET_5_0 + ); + private static FrameworkStrategy defaultFramework = FrameworkStrategy.NETSTANDARD_2_0; + protected final Map frameworks; + protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; + protected String clientPackage = "Org.OpenAPITools.Client"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + // Defines TargetFrameworkVersion in csproj files + protected String targetFramework = defaultFramework.name; + protected String testTargetFramework = defaultFramework.testTargetFramework; + + // Defines nuget identifiers for target framework + protected String targetFrameworkNuget = targetFramework; + + protected boolean supportsRetry = Boolean.TRUE; + protected boolean supportsAsync = Boolean.TRUE; + protected boolean netStandard = Boolean.FALSE; + + protected boolean validatable = Boolean.TRUE; + protected Map regexModifiers; + // By default, generated code is considered public + protected boolean nonPublicApi = Boolean.FALSE; + + protected boolean caseInsensitiveResponseHeaders = Boolean.FALSE; + protected String releaseNote = "Minor update"; + protected String licenseId; + protected String packageTags; + protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup + + protected boolean needsCustomHttpMethod = false; + protected boolean needsUriBuilder = false; + + public CSharpNetCoreReducedClientCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .securityFeatures(EnumSet.of( + SecurityFeature.OAuth2_Implicit, + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .includeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .includeParameterFeatures( + ParameterFeature.Cookie + ) + .includeClientModificationFeatures( + ClientModificationFeature.BasePath, + ClientModificationFeature.UserAgent + ) + ); + + // mapped non-nullable type without ? + typeMapping = new HashMap(); + typeMapping.put("string", "string"); + typeMapping.put("binary", "byte[]"); + typeMapping.put("ByteArray", "byte[]"); + typeMapping.put("boolean", "bool"); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("double", "double"); + typeMapping.put("number", "decimal"); + typeMapping.put("decimal", "decimal"); + typeMapping.put("DateTime", "DateTime"); + typeMapping.put("date", "DateTime"); + typeMapping.put("file", "System.IO.Stream"); + typeMapping.put("array", "List"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("object", "Object"); + typeMapping.put("UUID", "Guid"); + typeMapping.put("URI", "string"); + typeMapping.put("AnyType", "Object"); + + setSupportNullable(Boolean.TRUE); + hideGenerationTimestamp = Boolean.TRUE; + supportsInheritance = true; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + embeddedTemplateDir = templateDir = "csharp-netcore"; + + cliOptions.clear(); + + // CLI options + addOption(CodegenConstants.PACKAGE_NAME, + "C# package name (convention: Title.Case).", + this.packageName); + + addOption(CodegenConstants.PACKAGE_VERSION, + "C# package version.", + this.packageVersion); + + addOption(CodegenConstants.SOURCE_FOLDER, + CodegenConstants.SOURCE_FOLDER_DESC, + sourceFolder); + + addOption(CodegenConstants.OPTIONAL_PROJECT_GUID, + CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, + null); + + addOption(CodegenConstants.INTERFACE_PREFIX, + CodegenConstants.INTERFACE_PREFIX_DESC, + interfacePrefix); + + addOption(CodegenConstants.LICENSE_ID, + CodegenConstants.LICENSE_ID_DESC, + this.licenseId); + + addOption(CodegenConstants.RELEASE_NOTE, + CodegenConstants.RELEASE_NOTE_DESC, + this.releaseNote); + + addOption(CodegenConstants.PACKAGE_TAGS, + CodegenConstants.PACKAGE_TAGS_DESC, + this.packageTags); + + CliOption framework = new CliOption( + CodegenConstants.DOTNET_FRAMEWORK, + CodegenConstants.DOTNET_FRAMEWORK_DESC + ); + + CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString()); + Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); + disallowAdditionalPropertiesIfNotPresentOpts.put("false", + "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); + disallowAdditionalPropertiesIfNotPresentOpts.put("true", + "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default."); + disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); + cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + this.setDisallowAdditionalPropertiesIfNotPresent(true); + + ImmutableMap.Builder frameworkBuilder = new ImmutableMap.Builder<>(); + for (FrameworkStrategy frameworkStrategy : frameworkStrategies) { + frameworkBuilder.put(frameworkStrategy.name, frameworkStrategy.description); + } + + frameworks = frameworkBuilder.build(); + + framework.defaultValue(this.targetFramework); + framework.setEnum(frameworks); + cliOptions.add(framework); + + CliOption modelPropertyNaming = new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC); + cliOptions.add(modelPropertyNaming.defaultValue("PascalCase")); + + // CLI Switches + addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES, + CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC, + this.nullReferenceTypesFlag); + + addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, + this.hideGenerationTimestamp); + + addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, + this.sortParamsByRequiredFlag); + + addSwitch(CodegenConstants.USE_DATETIME_OFFSET, + CodegenConstants.USE_DATETIME_OFFSET_DESC, + this.useDateTimeOffsetFlag); + + addSwitch(CodegenConstants.USE_COLLECTION, + CodegenConstants.USE_COLLECTION_DESC, + this.useCollection); + + addSwitch(CodegenConstants.RETURN_ICOLLECTION, + CodegenConstants.RETURN_ICOLLECTION_DESC, + this.returnICollection); + + addSwitch(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, + "C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).", + this.optionalMethodArgumentFlag); + + addSwitch(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, + CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC, + this.optionalAssemblyInfoFlag); + + addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, + CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, + this.optionalEmitDefaultValuesFlag); + + addSwitch(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, + CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC, + this.conditionalSerialization); + + addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, + CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, + this.optionalProjectFileFlag); + + // NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo + // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx + // to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen + // should rely on default public visibility. + addSwitch(CodegenConstants.NON_PUBLIC_API, + CodegenConstants.NON_PUBLIC_API_DESC, + this.nonPublicApi); + + addSwitch(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC, + this.allowUnicodeIdentifiers); + + addSwitch(CodegenConstants.NETCORE_PROJECT_FILE, + CodegenConstants.NETCORE_PROJECT_FILE_DESC, + this.netCoreProjectFileFlag); + + addSwitch(CodegenConstants.VALIDATABLE, + CodegenConstants.VALIDATABLE_DESC, + this.validatable); + + addSwitch(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, + CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC, + this.caseInsensitiveResponseHeaders); + + addSwitch(CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS, + CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS_DESC, + this.caseInsensitiveResponseHeaders); + + regexModifiers = new HashMap<>(); + regexModifiers.put('i', "IgnoreCase"); + regexModifiers.put('m', "Multiline"); + regexModifiers.put('s', "Singleline"); + regexModifiers.put('x', "IgnorePatternWhitespace"); + + supportedLibraries.put(HTTPCLIENT, "HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) " + + "(Experimental. May subject to breaking changes without further notice.)"); + supportedLibraries.put(RESTSHARP, "RestSharp (https://github.com/restsharp/RestSharp)"); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + // set RESTSHARP as the default + libraryOption.setDefault(RESTSHARP); + cliOptions.add(libraryOption); + setLibrary(RESTSHARP); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + apiPackage(); + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + CodegenModel codegenModel = super.fromModel(name, model); + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) { + final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + if (parentModel != null) { + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + if (codegenModel.hasEnums) { + codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + + Map propertyHash = new HashMap<>(codegenModel.vars.size()); + for (final CodegenProperty property : codegenModel.vars) { + propertyHash.put(property.name, property); + } + + for (final CodegenProperty property : codegenModel.readWriteVars) { + if (property.defaultValue == null && parentCodegenModel.discriminator != null && property.name.equals(parentCodegenModel.discriminator.getPropertyName())) { + property.defaultValue = "\"" + name + "\""; + } + } + + CodegenProperty last = null; + for (final CodegenProperty property : parentCodegenModel.vars) { + // helper list of parentVars simplifies templating + if (!propertyHash.containsKey(property.name)) { + final CodegenProperty parentVar = property.clone(); + parentVar.isInherited = true; + last = parentVar; + LOGGER.debug("adding parent variable {}", property.name); + codegenModel.parentVars.add(parentVar); + } + } + } + } + + // Cleanup possible duplicates. Currently, readWriteVars can contain the same property twice. May or may not be isolated to C#. + if (codegenModel != null && codegenModel.readWriteVars != null && codegenModel.readWriteVars.size() > 1) { + int length = codegenModel.readWriteVars.size() - 1; + for (int i = length; i > (length / 2); i--) { + final CodegenProperty codegenProperty = codegenModel.readWriteVars.get(i); + // If the property at current index is found earlier in the list, remove this last instance. + if (codegenModel.readWriteVars.indexOf(codegenProperty) < i) { + codegenModel.readWriteVars.remove(i); + } + } + } + + return codegenModel; + } + + @Override + public String getHelp() { + return "Generates a C# client library (.NET Standard, .NET Core)."; + } + + public String getModelPropertyNaming() { + return this.modelPropertyNaming; + } + + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + @Override + public String getName() { + return "csharp-netcore"; + } + + public String getNameUsingModelPropertyNaming(String name) { + switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + @Override + public String getNullableType(Schema p, String type) { + if (languageSpecificPrimitives.contains(type)) { + if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { + return type + "?"; + } else { + return type; + } + } else { + return null; + } + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public boolean isNonPublicApi() { + return nonPublicApi; + } + + public void setNonPublicApi(final boolean nonPublicApi) { + this.nonPublicApi = nonPublicApi; + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + modelPackage(); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + postProcessEmitDefaultValue(property.vendorExtensions); + + super.postProcessModelProperty(model, property); + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + postProcessEmitDefaultValue(parameter.vendorExtensions); + super.postProcessParameter(parameter); + } + + /* + * The pattern spec follows the Perl convention and style of modifiers. .NET + * does not support this syntax directly so we need to convert the pattern to a .NET compatible + * format and apply modifiers in a compatible way. + * See https://msdn.microsoft.com/en-us/library/yd1hzczs(v=vs.110).aspx for .NET options. + */ + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if (pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. " + pattern + " is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\'").replace("\"", "\"\""); + List modifiers = new ArrayList(); + + // perl requires an explicit modifier to be culture specific and .NET is the reverse. + modifiers.add("CultureInvariant"); + + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } else if (c == 'l') { + modifiers.remove("CultureInvariant"); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } + + public void postProcessEmitDefaultValue(Map vendorExtensions) { + vendorExtensions.put("x-emit-default-value", optionalEmitDefaultValuesFlag); + } + + @Override + public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { + // To avoid unexpected behaviors when options are passed programmatically such as { "supportsAsync": "" } + return super.processCompiler(compiler).emptyStringIsFalse(true); + } + + @Override + public void processOpts() { + this.setLegacyDiscriminatorBehavior(false); + + super.processOpts(); + + /* + * NOTE: When supporting boolean additionalProperties, you should read the value and write it back as a boolean. + * This avoids oddities where additionalProperties contains "false" rather than false, which will cause the + * templating engine to behave unexpectedly. + * + * Use the pattern: + * if (additionalProperties.containsKey(prop)) convertPropertyToBooleanAndWriteBack(prop); + */ + + if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { + this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.parseBoolean(additionalProperties + .get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) { + setOptionalEmitDefaultValuesFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, optionalEmitDefaultValuesFlag); + } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)) { + setConditionalSerialization(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, conditionalSerialization); + } + + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } + + if (isEmpty(apiPackage)) { + setApiPackage("Api"); + } + if (isEmpty(modelPackage)) { + setModelPackage("Model"); + } + + clientPackage = "Client"; + + if (RESTSHARP.equals(getLibrary())) { + additionalProperties.put("useRestSharp", true); + needsCustomHttpMethod = true; + } else if (HTTPCLIENT.equals(getLibrary())) { + setLibrary(HTTPCLIENT); + additionalProperties.put("useHttpClient", true); + needsUriBuilder = true; + } else { + throw new RuntimeException("Invalid HTTP library " + getLibrary() + ". Only restsharp, httpclient are supported."); + } + + String inputFramework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name); + String[] frameworks; + List strategies = new ArrayList<>(); + + if (inputFramework.contains(";")) { + // multiple target framework + frameworks = inputFramework.split(";"); + additionalProperties.put("multiTarget", true); + } else { + // just a single value + frameworks = new String [] {inputFramework}; + } + + for (String framework : frameworks) { + boolean strategyMatched = false; + for (FrameworkStrategy frameworkStrategy : frameworkStrategies) { + if (framework.equals(frameworkStrategy.name)) { + strategies.add(frameworkStrategy); + strategyMatched = true; + } + + if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) { + LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later."); + } + } + + if (!strategyMatched) { + // throws exception if the input targetFramework is invalid + throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " + + framework + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } + } + + configureAdditionalPropertiesForFrameworks(additionalProperties, strategies); + setTargetFrameworkNuget(strategies); + setTargetFramework(strategies); + setTestTargetFramework(strategies); + + setSupportsAsync(Boolean.TRUE); + setNetStandard(strategies.stream().anyMatch(p -> Boolean.TRUE.equals(p.isNetStandard))); + + if (!netStandard) { + setNetCoreProjectFileFlag(true); + } + + if (additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { + LOGGER.warn("{} is not supported in the .NET Standard generator.", CodegenConstants.GENERATE_PROPERTY_CHANGED); + additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); + } + + final AtomicReference excludeTests = new AtomicReference<>(); + syncBooleanProperty(additionalProperties, CodegenConstants.EXCLUDE_TESTS, excludeTests::set, false); + + syncStringProperty(additionalProperties, "clientPackage", (s) -> { }, clientPackage); + + syncStringProperty(additionalProperties, CodegenConstants.API_PACKAGE, this::setApiPackage, apiPackage); + syncStringProperty(additionalProperties, CodegenConstants.MODEL_PACKAGE, this::setModelPackage, modelPackage); + syncStringProperty(additionalProperties, CodegenConstants.OPTIONAL_PROJECT_GUID, this::setPackageGuid, packageGuid); + syncStringProperty(additionalProperties, "targetFrameworkNuget", this::setTargetFrameworkNuget, this.targetFrameworkNuget); + syncStringProperty(additionalProperties, "testTargetFramework", this::setTestTargetFramework, this.testTargetFramework); + + syncBooleanProperty(additionalProperties, "netStandard", this::setNetStandard, this.netStandard); + + syncBooleanProperty(additionalProperties, CodegenConstants.VALIDATABLE, this::setValidatable, this.validatable); + syncBooleanProperty(additionalProperties, CodegenConstants.SUPPORTS_ASYNC, this::setSupportsAsync, this.supportsAsync); + syncBooleanProperty(additionalProperties, SUPPORTS_RETRY, this::setSupportsRetry, this.supportsRetry); + syncBooleanProperty(additionalProperties, CodegenConstants.OPTIONAL_METHOD_ARGUMENT, this::setOptionalMethodArgumentFlag, optionalMethodArgumentFlag); + syncBooleanProperty(additionalProperties, CodegenConstants.NON_PUBLIC_API, this::setNonPublicApi, isNonPublicApi()); + syncBooleanProperty(additionalProperties, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup, this.useOneOfDiscriminatorLookup); + + final String testPackageName = testPackageName(); + String packageFolder = sourceFolder + File.separator + packageName; + String clientPackageDir = packageFolder + File.separator + clientPackage; + String modelPackageDir = packageFolder + File.separator + modelPackage; + String testPackageFolder = testFolder + File.separator + testPackageName; + + additionalProperties.put("testPackageName", testPackageName); + + //Compute the relative path to the bin directory where the external assemblies live + //This is necessary to properly generate the project file + int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length(); + String binRelativePath = "..\\"; + for (int i = 0; i < packageDepth; i = i + 1) { + binRelativePath += "..\\"; + } + binRelativePath += "vendor"; + additionalProperties.put("binRelativePath", binRelativePath); + + if(HTTPCLIENT.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); + typeMapping.put("file", "FileParameter"); + } + + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); + supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", clientPackageDir, "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs")); + supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs")); + supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); + if(needsCustomHttpMethod) { + supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs")); + } + if(needsUriBuilder) { + supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs")); + } + if (ProcessUtils.hasHttpSignatureMethods(openAPI)) { + supportingFiles.add(new SupportingFile("HttpSigningConfiguration.mustache", clientPackageDir, "HttpSigningConfiguration.cs")); + } + if (supportsAsync) { + supportingFiles.add(new SupportingFile("IAsynchronousClient.mustache", clientPackageDir, "IAsynchronousClient.cs")); + } + supportingFiles.add(new SupportingFile("ISynchronousClient.mustache", clientPackageDir, "ISynchronousClient.cs")); + supportingFiles.add(new SupportingFile("RequestOptions.mustache", clientPackageDir, "RequestOptions.cs")); + supportingFiles.add(new SupportingFile("Multimap.mustache", clientPackageDir, "Multimap.cs")); + + if (supportsRetry) { + supportingFiles.add(new SupportingFile("RetryConfiguration.mustache", clientPackageDir, "RetryConfiguration.cs")); + } + + supportingFiles.add(new SupportingFile("IReadableConfiguration.mustache", + clientPackageDir, "IReadableConfiguration.cs")); + supportingFiles.add(new SupportingFile("GlobalConfiguration.mustache", + clientPackageDir, "GlobalConfiguration.cs")); + + // Only write out test related files if excludeTests is unset or explicitly set to false (see start of this method) + if (Boolean.FALSE.equals(excludeTests.get())) { + modelTestTemplateFiles.put("model_test.mustache", ".cs"); + apiTestTemplateFiles.put("api_test.mustache", ".cs"); + } + + 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("appveyor.mustache", "", "appveyor.yml")); + supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs")); + + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + } + + public void setNetStandard(Boolean netStandard) { + this.netStandard = netStandard; + } + + public void setOptionalAssemblyInfoFlag(boolean flag) { + this.optionalAssemblyInfoFlag = flag; + } + + public void setOptionalEmitDefaultValuesFlag(boolean flag) { + this.optionalEmitDefaultValuesFlag = flag; + } + + public void setConditionalSerialization(boolean flag){ + this.conditionalSerialization = flag; + } + + public void setOptionalProjectFileFlag(boolean flag) { + this.optionalProjectFileFlag = flag; + } + + public void setPackageGuid(String packageGuid) { + this.packageGuid = packageGuid; + } + + @Override + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + @Override + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setSupportsAsync(Boolean supportsAsync) { + this.supportsAsync = supportsAsync; + } + + public void setSupportsRetry(Boolean supportsRetry) { + this.supportsRetry = supportsRetry; + } + + public void setTargetFramework(String dotnetFramework) { + if (!frameworks.containsKey(dotnetFramework)) { + throw new IllegalArgumentException("Invalid .NET framework version: " + + dotnetFramework + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } else { + this.targetFramework = dotnetFramework; + } + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); + } + + public void setTargetFramework(List strategies) { + for (FrameworkStrategy strategy : strategies) { + if (!frameworks.containsKey(strategy.name)) { + throw new IllegalArgumentException("Invalid .NET framework version: " + + strategy.name + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } + } + this.targetFramework = strategies.stream().map(p -> p.name) + .collect(Collectors.joining(";")); + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); + } + + public void setTestTargetFramework(String testTargetFramework) { + this.testTargetFramework = testTargetFramework; + } + + public void setTestTargetFramework(List strategies) { + this.testTargetFramework = strategies.stream().map(p -> p.testTargetFramework) + .collect(Collectors.joining(";")); + } + + public void setTargetFrameworkNuget(String targetFrameworkNuget) { + this.targetFrameworkNuget = targetFrameworkNuget; + } + + public void setTargetFrameworkNuget(List strategies) { + this.targetFrameworkNuget = strategies.stream().map(p -> p.getNugetFrameworkIdentifier()) + .collect(Collectors.joining(";")); + } + + public void setValidatable(boolean validatable) { + this.validatable = validatable; + } + + public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) { + this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders; + } + + public void setLicenseId(String licenseId) { + this.licenseId = licenseId; + } + + @Override + public void setReleaseNote(String releaseNote) { + this.releaseNote = releaseNote; + } + + public void setPackageTags(String packageTags) { + this.packageTags = packageTags; + } + + public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) { + this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup; + } + + public boolean getUseOneOfDiscriminatorLookup() { + return this.useOneOfDiscriminatorLookup; + } + + @Override + public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "Empty"; + } + + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return camelize(getSymbolName(value)); + } + + // number + if (datatype.startsWith("int") || datatype.startsWith("long") || + datatype.startsWith("double") || datatype.startsWith("float")) { + String varName = "NUMBER_" + value; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // string + String var = value.replaceAll(" ", "_"); + var = camelize(var); + var = var.replaceAll("\\W+", ""); + + if (var.matches("\\d.*")) { + return "_" + var; + } else { + return var; + } + } + + @Override + public String toModelDocFilename(String name) { + return toModelFilename(name); + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); + + // if it's all upper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + name = getNameUsingModelPropertyNaming(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + // for function names in the model, escape with the "Property" prefix + if (propertySpecialKeywords.contains(name)) { + return camelize("property_" + name); + } + + return name; + } + + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (parentCodegenModel.hasEnums) { + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + boolean removedChildEnum = false; + for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenProperty.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenProperty)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildEnum = true; + } + } + } + } + + if (removedChildEnum) { + codegenModel.vars = codegenProperties; + } + } + + return codegenModel; + } + + private void syncBooleanProperty(final Map additionalProperties, final String key, final Consumer setter, final Boolean defaultValue) { + if (additionalProperties.containsKey(key)) { + setter.accept(convertPropertyToBooleanAndWriteBack(key)); + } else { + additionalProperties.put(key, defaultValue); + setter.accept(defaultValue); + } + } + + private void syncStringProperty(final Map additionalProperties, final String key, final Consumer setter, final String defaultValue) { + if (additionalProperties.containsKey(key)) { + setter.accept((String) additionalProperties.get(key)); + } else { + additionalProperties.put(key, defaultValue); + setter.accept(defaultValue); + } + } + + // https://docs.microsoft.com/en-us/dotnet/standard/net-standard + @SuppressWarnings("Duplicates") + private static abstract class FrameworkStrategy { + + private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + + static FrameworkStrategy NETSTANDARD_1_3 = new FrameworkStrategy("netstandard1.3", ".NET Standard 1.3 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_4 = new FrameworkStrategy("netstandard1.4", ".NET Standard 1.4 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_5 = new FrameworkStrategy("netstandard1.5", ".NET Standard 1.5 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_6 = new FrameworkStrategy("netstandard1.6", ".NET Standard 1.6 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_2_0 = new FrameworkStrategy("netstandard2.0", ".NET Standard 2.0 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_2_1 = new FrameworkStrategy("netstandard2.1", ".NET Standard 2.1 compatible", "netcoreapp3.0") { + }; + static FrameworkStrategy NETCOREAPP_2_0 = new FrameworkStrategy("netcoreapp2.0", ".NET Core 2.0 compatible", "netcoreapp2.0", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_2_1 = new FrameworkStrategy("netcoreapp2.1", ".NET Core 2.1 compatible", "netcoreapp2.1", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_3_0 = new FrameworkStrategy("netcoreapp3.0", ".NET Core 3.0 compatible", "netcoreapp3.0", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_3_1 = new FrameworkStrategy("netcoreapp3.1", ".NET Core 3.1 compatible", "netcoreapp3.1", Boolean.FALSE) { + }; + static FrameworkStrategy NETFRAMEWORK_4_7 = new FrameworkStrategy("net47", ".NET Framework 4.7 compatible", "net47", Boolean.FALSE) { + }; + static FrameworkStrategy NET_5_0 = new FrameworkStrategy("net5.0", ".NET 5.0 compatible", "net5.0", Boolean.FALSE) { + }; + protected String name; + protected String description; + protected String testTargetFramework; + private Boolean isNetStandard = Boolean.TRUE; + + FrameworkStrategy(String name, String description, String testTargetFramework) { + this.name = name; + this.description = description; + this.testTargetFramework = testTargetFramework; + } + + FrameworkStrategy(String name, String description, String testTargetFramework, Boolean isNetStandard) { + this.name = name; + this.description = description; + this.testTargetFramework = testTargetFramework; + this.isNetStandard = isNetStandard; + } + + protected void configureAdditionalProperties(final Map properties) { + properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.name); + + // not intended to be user-settable + properties.put(TARGET_FRAMEWORK_IDENTIFIER, this.getTargetFrameworkIdentifier()); + properties.put(TARGET_FRAMEWORK_VERSION, this.getTargetFrameworkVersion()); + properties.putIfAbsent(MCS_NET_VERSION_KEY, "4.6-api"); + + properties.put(NET_STANDARD, this.isNetStandard); + if (properties.containsKey(SUPPORTS_UWP)) { + LOGGER.warn(".NET {} generator does not support the UWP option. Use the csharp generator instead.", + this.name); + properties.remove(SUPPORTS_UWP); + } + } + + protected String getNugetFrameworkIdentifier() { + return this.name.toLowerCase(Locale.ROOT); + } + + protected String getTargetFrameworkIdentifier() { + if (this.isNetStandard) return ".NETStandard"; + else return ".NETCoreApp"; + } + + protected String getTargetFrameworkVersion() { + if (this.isNetStandard) return "v" + this.name.replace("netstandard", ""); + else return "v" + this.name.replace("netcoreapp", ""); + } + } + + protected void configureAdditionalPropertiesForFrameworks(final Map properties, List strategies) { + properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, strategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(";"))); + + // not intended to be user-settable + properties.put(TARGET_FRAMEWORK_IDENTIFIER, strategies.stream() + .map(p -> p.getTargetFrameworkIdentifier()) + .collect(Collectors.joining(";"))); + properties.put(TARGET_FRAMEWORK_VERSION, strategies.stream() + .map(p -> p.getTargetFrameworkVersion()) + .collect(Collectors.joining(";"))); + properties.putIfAbsent(MCS_NET_VERSION_KEY, "4.6-api"); + + properties.put(NET_STANDARD, strategies.stream().anyMatch(p -> Boolean.TRUE.equals(p.isNetStandard))); + } + + /** + * Return the instantiation type of the property, especially for map and array + * + * @param schema property schema + * @return string presentation of the instantiation type of the property + */ + @Override + public String toInstantiationType(Schema schema) { + if (ModelUtils.isMapSchema(schema)) { + Schema additionalProperties = getAdditionalProperties(schema); + String inner = getSchemaType(additionalProperties); + if (ModelUtils.isMapSchema(additionalProperties)) { + inner = toInstantiationType(additionalProperties); + } + return instantiationTypes.get("map") + ""; + } else if (ModelUtils.isArraySchema(schema)) { + ArraySchema arraySchema = (ArraySchema) schema; + String inner = getSchemaType(arraySchema.getItems()); + return instantiationTypes.get("array") + "<" + inner + ">"; + } else { + return null; + } + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessModels(Map objs) { + objs = super.postProcessModels(objs); + List models = (List) objs.get("models"); + + // add implements for serializable/parcelable to all models + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + + if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) { + // if oneOf contains "null" type + cm.isNullable = true; + cm.oneOf.remove("ModelNull"); + } + + if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) { + // if anyOf contains "null" type + cm.isNullable = true; + cm.anyOf.remove("ModelNull"); + } + } + + return objs; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); + System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } + + @Override + protected void updateModelForObject(CodegenModel m, Schema schema) { + /** + * we have a custom version of this function so we only set isMap to true if + * ModelUtils.isMapSchema + * In other generators, isMap is true for all type object schemas + */ + if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) { + // passing null to allProperties and allRequired as there's no parent + addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); + } + if (ModelUtils.isMapSchema(schema)) { + // an object or anyType composed schema that has additionalProperties set + addAdditionPropertiesToCodeGenModel(m, schema); + } else { + m.setIsMap(false); + if (ModelUtils.isFreeFormObject(openAPI, schema)) { + // non-composed object type with no properties + additionalProperties + // additionalProperties must be null, ObjectSchema, or empty Schema + addAdditionPropertiesToCodeGenModel(m, schema); + } + } + // process 'additionalProperties' + setAddProps(schema, m); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java new file mode 100644 index 00000000000..f2ab9939c34 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java @@ -0,0 +1,82 @@ +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen { + public static final String PROJECT_NAME = "projectName"; + + final Logger LOGGER = LoggerFactory.getLogger(CsharpNetcoreFunctionsServerCodegen.class); + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "csharp-netcore-functions"; + } + + public String getHelp() { + return "Generates a csharp server."; + } + + public CsharpNetcoreFunctionsServerCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "csharp"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("functions.mustache", ".cs"); + embeddedTemplateDir = templateDir = "csharp-netcore-functions"; + apiPackage = "Apis"; + modelPackage = "Models"; + String clientPackageDir = "generatedSrc/Client"; + supportingFiles.add(new SupportingFile("README.mustache", "generatedSrc", "README.md")); + supportingFiles.add(new SupportingFile("project.mustache", "generatedSrc", "project.json")); + + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", + clientPackageDir, "IApiAccessor.cs")); + supportingFiles.add(new SupportingFile("Configuration.mustache", + clientPackageDir, "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + clientPackageDir, "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + clientPackageDir, "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", + clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", + clientPackageDir, "ExceptionFactory.cs")); + supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", + clientPackageDir, "OpenAPIDateConverter.cs")); + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + "generatedSrc" + File.separator + "Functions"; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + "generatedSrc" + File.separator + "Models"; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/Docs").replace('/', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + "Tests" + File.separator + "Tests" + File.separator + apiPackage(); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java index 9acfe364003..5f438eb6f8b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java @@ -323,6 +323,21 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // enums are generated with built_value and make use of BuiltSet model.imports.add("BuiltSet"); } + + if (property.isContainer) { + // Figure out if there are any container type additionalProperties + // that need a custom serializer builder factory added. + final CodegenProperty items = property.items; + if (items.getAdditionalProperties() != null) { + addBuiltValueSerializer(new BuiltValueSerializer( + items.isArray, + items.getUniqueItems(), + items.isMap, + items.items.isNullable, + items.getAdditionalProperties().dataType + )); + } + } } } @@ -332,7 +347,6 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); - Set> serializers = new HashSet<>(); Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { @@ -370,12 +384,13 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // Generate serializer factories for all container type parameters. // But skip binary and file parameters, JSON serializers don't make sense there. if (param.isContainer && !(param.isBinary || param.isFile )) { - final Map serializer = new HashMap<>(); - serializer.put("isArray", param.isArray); - serializer.put("uniqueItems", param.uniqueItems); - serializer.put("isMap", param.isMap); - serializer.put("baseType", param.baseType); - serializers.add(serializer); + addBuiltValueSerializer(new BuiltValueSerializer( + param.isArray, + param.uniqueItems, + param.isMap, + param.items.isNullable, + param.baseType + )); } } @@ -387,17 +402,17 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // Generate serializer factories for response types. // But skip binary and file response, JSON serializers don't make sense there. if (op.returnContainer != null && !(op.isResponseBinary || op.isResponseFile)) { - final Map serializer = new HashMap<>(); - serializer.put("isArray", Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer)); - serializer.put("uniqueItems", op.uniqueItems); - serializer.put("isMap", Objects.equals("map", op.returnContainer)); - serializer.put("baseType", op.returnBaseType); - serializers.add(serializer); + addBuiltValueSerializer(new BuiltValueSerializer( + Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer), + op.uniqueItems, + Objects.equals("map", op.returnContainer), + false, + op.returnBaseType + )); } } objs.put("imports", resultImports.stream().sorted().collect(Collectors.toList())); - objs.put("serializers", serializers); return objs; } @@ -410,6 +425,19 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { }); } + /** + * Adds the serializer to the global list of custom built_value serializers. + * @param serializer + */ + private void addBuiltValueSerializer(BuiltValueSerializer serializer) { + System.out.println("######## Add serializer!"); + additionalProperties.compute("builtValueSerializers", (k, v) -> { + Set serializers = v == null ? Sets.newHashSet() : ((Set) v); + serializers.add(serializer); + return serializers; + }); + } + private Set rewriteImports(Set originalImports, boolean isModel) { Set resultImports = Sets.newHashSet(); for (String modelImport : originalImports) { @@ -428,4 +456,58 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { } return resultImports; } + + static class BuiltValueSerializer { + + final boolean isArray; + + final boolean uniqueItems; + + final boolean isMap; + + final boolean isNullable; + + final String dataType; + + private BuiltValueSerializer(boolean isArray, boolean uniqueItems, boolean isMap, boolean isNullable, String dataType) { + this.isArray = isArray; + this.uniqueItems = uniqueItems; + this.isMap = isMap; + this.isNullable = isNullable; + this.dataType = dataType; + } + + public boolean isArray() { + return isArray; + } + + public boolean isUniqueItems() { + return uniqueItems; + } + + public boolean isMap() { + return isMap; + } + + public boolean isNullable() { + return isNullable; + } + + public String getDataType() { + return dataType; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + BuiltValueSerializer that = (BuiltValueSerializer) o; + return isArray == that.isArray && uniqueItems == that.uniqueItems && isMap == that.isMap && isNullable == that.isNullable && dataType.equals(that.dataType); + } + + @Override + public int hashCode() { + return Objects.hash(isArray, uniqueItems, isMap, isNullable, dataType); + } + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 9903908d4e0..62c9d6dcc5f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -613,7 +613,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig return "%{}"; } // Primitive return type, don't even try to decode - if (baseType == null || (simpleType && primitiveType)) { + if (baseType == null || (containerType == null && primitiveType)) { return "false"; } else if (isArray && languageSpecificPrimitives().contains(baseType)) { return "[]"; @@ -733,16 +733,13 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig StringBuilder returnEntry = new StringBuilder(); if (exResponse.baseType == null) { returnEntry.append("nil"); - } else if (exResponse.simpleType) { + } else if (exResponse.containerType == null) { // not container (array, map, set) if (!exResponse.primitiveType) { returnEntry.append(moduleName); returnEntry.append(".Model."); } returnEntry.append(exResponse.baseType); returnEntry.append(".t"); - } else if (exResponse.containerType == null) { - returnEntry.append(returnBaseType); - returnEntry.append(".t"); } else { if (exResponse.containerType.equals("array") || exResponse.containerType.equals("set")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java index 138b1c54356..05b5b92df39 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java @@ -215,6 +215,9 @@ public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements } } + String modelPath = packagePath() + File.separatorChar + modelPackage.replace('.', File.separatorChar); + String apiPath = packagePath() + File.separatorChar + apiPackage.replace('.', File.separatorChar); + String readmePath = "README.md"; String readmeTemplate = "README.mustache"; if (generateSourceCodeOnly) { @@ -237,8 +240,8 @@ public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements } supportingFiles.add(new SupportingFile("configuration.mustache", packagePath(), "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", packagePath(), "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", packagePath() + File.separatorChar + apiPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPath, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPath, "__init__.py")); // If the package name consists of dots(openapi.client), then we need to create the directory structure like openapi/client with __init__ files. String[] packageNameSplits = packageName.split("\\."); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 31614ac9b65..2cd6ebd8dd4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -66,6 +66,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig public static final String SWIFT_PACKAGE_PATH = "swiftPackagePath"; public static final String USE_CLASSES = "useClasses"; public static final String USE_BACKTICK_ESCAPES = "useBacktickEscapes"; + public static final String GENERATE_FROZEN_ENUMS = "generateFrozenEnums"; public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES = "generateModelAdditionalProperties"; public static final String HASHABLE_MODELS = "hashableModels"; public static final String MAP_FILE_BINARY_TO_DATA = "mapFileBinaryToData"; @@ -90,6 +91,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig protected boolean useClasses = false; protected boolean useBacktickEscapes = false; protected boolean generateModelAdditionalProperties = true; + protected boolean generateFrozenEnums = true; protected boolean hashableModels = true; protected boolean mapFileBinaryToData = false; protected String[] responseAs = new String[0]; @@ -281,6 +283,9 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig cliOptions.add(new CliOption(USE_BACKTICK_ESCAPES, "Escape reserved words using backticks (default: false)") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(GENERATE_FROZEN_ENUMS, + "Generate frozen enums (default: true)") + .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(GENERATE_MODEL_ADDITIONAL_PROPERTIES, "Generate model additional properties (default: true)") .defaultValue(Boolean.TRUE.toString())); @@ -485,6 +490,13 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig setUseBacktickEscapes(convertPropertyToBooleanAndWriteBack(USE_BACKTICK_ESCAPES)); } + // Setup generateFrozenEnums option. If true, enums will strictly include + // cases matching the spec. If false, enums will also include an extra catch-all case. + if (additionalProperties.containsKey(GENERATE_FROZEN_ENUMS)) { + setGenerateFrozenEnums(convertPropertyToBooleanAndWriteBack(GENERATE_FROZEN_ENUMS)); + } + additionalProperties.put(GENERATE_FROZEN_ENUMS, generateFrozenEnums); + if (additionalProperties.containsKey(GENERATE_MODEL_ADDITIONAL_PROPERTIES)) { setGenerateModelAdditionalProperties(convertPropertyToBooleanAndWriteBack(GENERATE_MODEL_ADDITIONAL_PROPERTIES)); } @@ -943,6 +955,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig this.useBacktickEscapes = useBacktickEscapes; } + public void setGenerateFrozenEnums(boolean generateFrozenEnums) { + this.generateFrozenEnums = generateFrozenEnums; + } + public void setGenerateModelAdditionalProperties(boolean generateModelAdditionalProperties) { this.generateModelAdditionalProperties = generateModelAdditionalProperties; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 758f2650f5a..d2ab116ab1e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -67,7 +67,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values."; public static final String QUERY_PARAM_OBJECT_FORMAT = "queryParamObjectFormat"; - protected String ngVersion = "12.2.12"; + protected String ngVersion = "13.0.1"; protected String npmRepository = null; private boolean useSingleRequestParameter = false; protected String serviceSuffix = "Service"; @@ -146,7 +146,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode @Override public String getHelp() { - return "Generates a TypeScript Angular (6.x - 12.x) client library."; + return "Generates a TypeScript Angular (6.x - 13.x) client library."; } @Override @@ -243,7 +243,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } else { additionalProperties.put(DELETE_ACCEPTS_BODY, false); } - + additionalProperties.put(NG_VERSION, ngVersion); if (additionalProperties.containsKey(API_MODULE_PREFIX)) { @@ -300,7 +300,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the typescript version compatible to the Angular version - if (ngVersion.atLeast("12.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("tsVersion", ">=4.4.2 <4.5.0"); + } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("tsVersion", ">=4.3.0 <4.4.0"); } else if (ngVersion.atLeast("11.0.0")) { additionalProperties.put("tsVersion", ">=4.0.0 <4.1.0"); @@ -318,7 +320,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the rxJS version compatible to the Angular version - if (ngVersion.atLeast("10.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("rxjsVersion", "7.4.0"); + } else if (ngVersion.atLeast("10.0.0")) { additionalProperties.put("rxjsVersion", "6.6.0"); } else if (ngVersion.atLeast("9.0.0")) { additionalProperties.put("rxjsVersion", "6.5.3"); @@ -334,7 +338,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode supportingFiles.add(new SupportingFile("ng-package.mustache", getIndexDirectory(), "ng-package.json")); // Specific ng-packagr configuration - if (ngVersion.atLeast("12.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("ngPackagrVersion", "13.0.3"); + additionalProperties.put("tsickleVersion", "0.43.0"); + } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("ngPackagrVersion", "12.2.1"); additionalProperties.put("tsickleVersion", "0.43.0"); } else if (ngVersion.atLeast("11.0.0")) { @@ -542,8 +549,19 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode setChildDiscriminatorValue(cm, child); } } + + // with tagged union, a child model doesn't extend the parent (all properties are just copied over) + // it means we don't need to import that parent any more if (cm.parent != null) { cm.imports.remove(cm.parent); + + // however, it's possible that the child model contains a recursive reference to the parent + // in order to support this case, we update the list of imports from properties once again + for (CodegenProperty cp: cm.allVars) { + addImportsForPropertyType(cm, cp); + } + removeSelfReferenceImports(cm); + } } // Add additional filename information for imports diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache index 91a7905d0bc..56477b8dc17 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache @@ -132,21 +132,9 @@ public class JSON { {{#models}} {{#model}} {{^isEnum}} - {{#oneOf}} - {{#-first}} + {{^hasChildren}} .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/-first}} - {{/oneOf}} - {{^oneOf}} - {{#anyOf}} - {{#-first}} - .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/-first}} - {{/anyOf}} - {{^anyOf}} - .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/anyOf}} - {{/oneOf}} + {{/hasChildren}} {{/isEnum}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache index df9dbc320d4..f7ad1e3a05a 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache @@ -379,6 +379,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens } }; {{/parcelableModel}} +{{^hasChildren}} public static HashSet openapiFields; public static HashSet openapiRequiredFields; @@ -442,4 +443,5 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens }.nullSafe(); } } +{{/hasChildren}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 78855ce50ad..727ec5d990f 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -23,6 +23,7 @@ org.openapitools.codegen.languages.CSharpClientCodegen org.openapitools.codegen.languages.CSharpNetCoreClientCodegen org.openapitools.codegen.languages.CSharpDotNet2ClientCodegen org.openapitools.codegen.languages.CSharpNancyFXServerCodegen +org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen org.openapitools.codegen.languages.DartClientCodegen org.openapitools.codegen.languages.DartDioClientCodegen org.openapitools.codegen.languages.DartDioNextClientCodegen diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index 48d810d038a..483ee5870f4 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -104,7 +104,7 @@ Operation Id:: {{nickname}} | {{code}} | {{message}} -| {{^simpleType}}{{dataType}}[<<{{baseType}}>>]{{/simpleType}} {{#simpleType}}<<{{dataType}}>>{{/simpleType}} +| {{#containerType}}{{dataType}}[<<{{baseType}}>>]{{/containerType}} {{^containerType}}<<{{dataType}}>>{{/containerType}} {{/responses}} |=== diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache new file mode 100644 index 00000000000..05e78204959 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache @@ -0,0 +1,68 @@ +{{>partial_header}} + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace {{packageName}}.{{modelPackage}} +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + {{>visibility}} abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache new file mode 100644 index 00000000000..65cbf8d76bc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache @@ -0,0 +1,867 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^netStandard}} +using System.Web; +{{/netStandard}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using RestSharp; +using RestSharp.Deserializers; +using RestSharpMethod = RestSharp.Method; +{{#useWebRequest}} +using System.Net.Http; +{{/useWebRequest}} +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} + +namespace {{packageName}}.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public T Deserialize(IRestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(IRestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + {{! NOTE: Any changes related to RestSharp should be done in this class. All other client classes are for extensibility by consumers.}} + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + {{>visibility}} partial class ApiClient : ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = {{packageName}}.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.GET; + break; + case HttpMethod.Post: + other = RestSharpMethod.POST; + break; + case HttpMethod.Put: + other = RestSharpMethod.PUT; + break; + case HttpMethod.Delete: + other = RestSharpMethod.DELETE; + break; + case HttpMethod.Head: + other = RestSharpMethod.HEAD; + break; + case HttpMethod.Options: + other = RestSharpMethod.OPTIONS; + break; + case HttpMethod.Patch: + other = RestSharpMethod.PATCH; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(Method(method)) + { + Resource = path, + JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) + }; + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + var bytes = ClientUtils.ReadAsBytes(fileParam.Value); + var fileStream = fileParam.Value as FileStream; + if (fileStream != null) + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + else + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + request.AddCookie(cookie.Name, cookie.Value); + } + } + + return request; + } + + private ApiResponse ToApiResponse(IRestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, IReadableConfiguration configuration) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + {{#supportsAsync}} + private async Task> ExecAsync(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + {{/supportsRetry}} + response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache new file mode 100644 index 00000000000..f7dadc5573c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache @@ -0,0 +1,60 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// API Exception + /// + {{>visibility}} class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache new file mode 100644 index 00000000000..161c2acd16c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache @@ -0,0 +1,158 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache new file mode 100644 index 00000000000..d5d937dc19f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache @@ -0,0 +1,40 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("{{packageTitle}}")] +[assembly: AssemblyDescription("{{packageDescription}}")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("{{packageCompany}}")] +[assembly: AssemblyProduct("{{packageProductName}}")] +[assembly: AssemblyCopyright("{{packageCopyright}}")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("{{packageVersion}}")] +[assembly: AssemblyFileVersion("{{packageVersion}}")] +{{^supportsAsync}} +// Settings which don't support asynchronous operations rely on non-public constructors +// This is due to how RestSharp requires the type constraint `where T : new()` in places it probably shouldn't. +[assembly: InternalsVisibleTo("RestSharp")] +[assembly: InternalsVisibleTo("NewtonSoft.Json")] +[assembly: InternalsVisibleTo("JsonSubTypes")] +{{/supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache new file mode 100644 index 00000000000..3c04dcdbd0c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache @@ -0,0 +1,239 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +{{#useCompareNetObjects}} +using KellermanSoftware.CompareNetObjects; +{{/useCompareNetObjects}} + +namespace {{packageName}}.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + {{#useCompareNetObjects}} + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static contstructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + {{/useCompareNetObjects}} + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache new file mode 100644 index 00000000000..ead56414441 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache @@ -0,0 +1,574 @@ +{{>partial_header}} + +using System; +{{^net35}} +using System.Collections.Concurrent; +{{/net35}} +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace {{packageName}}.Client +{ + /// + /// Represents a set of configuration settings + /// + {{>visibility}} class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "{{packageVersion}}"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + {{^netStandard}} + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + {{/netStandard}} + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for acessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + {{#servers.0}} + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + {{/servers.0}} + {{#hasHttpSignatureMethods}} + + /// + /// HttpSigning configuration + /// + private HttpSigningConfiguration _HttpSigningConfiguration = null; + {{/hasHttpSignatureMethods}} + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"; + BasePath = "{{{basePath}}}"; + DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKey = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKeyPrefix = new {{^net35}}Concurrent{{/net35}}Dictionary(); + {{#servers}} + {{#-first}} + Servers = new List>() + { + {{/-first}} + { + new Dictionary { + {"url", "{{{url}}}"}, + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {{#variables}} + {{#-first}} + { + "variables", new Dictionary { + {{/-first}} + { + "{{{name}}}", new Dictionary { + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {"default_value", "{{{defaultValue}}}"}, + {{#enumValues}} + {{#-first}} + { + "enum_values", new List() { + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/enumValues}} + } + }{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/variables}} + } + }{{^-last}},{{/-last}} + {{#-last}} + }; + {{/-last}} + {{/servers}} + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "{{{basePath}}}") : this() + { + if (string.{{^net35}}IsNullOrWhiteSpace{{/net35}}{{#net35}}IsNullOrEmpty{{/net35}}(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + {{#servers.0}} + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + if (index < 0 || index >= Servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = Servers[index]; + string url = (string)server["url"]; + + // go through variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use defualt value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + + return url; + } + {{/servers.0}} + {{#hasHttpSignatureMethods}} + + /// + /// Gets and Sets the HttpSigningConfiuration + /// + public HttpSigningConfiguration HttpSigningConfiguration + { + get { return _HttpSigningConfiguration; } + set { _HttpSigningConfiguration = value; } + } + {{/hasHttpSignatureMethods}} + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK ({{{packageName}}}) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: {{{version}}}\n"; + report += " SDK Package Version: {{{packageVersion}}}\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + {{#hasHttpSignatureMethods}} + HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, + {{/hasHttpSignatureMethods}} + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat + }; + return config; + } + #endregion Static Members + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache new file mode 100644 index 00000000000..4a141f6f1ae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache @@ -0,0 +1,14 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + {{>visibility}} delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache new file mode 100644 index 00000000000..bdfa4b99cc1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache @@ -0,0 +1,59 @@ +{{>partial_header}} + +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache new file mode 100644 index 00000000000..904a042a9ac --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache @@ -0,0 +1,25 @@ +{{>partial_header}} + +namespace {{packageName}}.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache new file mode 100644 index 00000000000..cc8c275e40b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache @@ -0,0 +1,757 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace {{packageName}}.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + #region + /// + /// Initailize the HashAlgorithm and SigningAlgorithm to default value + /// + public HttpSigningConfiguration() + { + HashAlgorithm = HashAlgorithmName.SHA256; + SigningAlgorithm = "PKCS1-v15"; + } + #endregion + + #region Properties + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validaty period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + #endregion + + #region enum + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + #endregion + + #region Methods + /// + /// Gets the Headers for HttpSigning + /// + /// Base path + /// HTTP method + /// Path + /// Request options + /// + internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) + { + const string HEADER_REQUEST_TARGET = "(request-target)"; + //The time when the HTTP signature expires. The API server should reject HTTP requests + //that have expired. + const string HEADER_EXPIRES = "(expires)"; + //The 'Date' header. + const string HEADER_DATE = "Date"; + //The 'Host' header. + const string HEADER_HOST = "Host"; + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + var HttpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + { + HttpSigningHeader.Add("(created)"); + } + + if (requestOptions.PathParameters != null) + { + foreach (var pathParam in requestOptions.PathParameters) + { + var tempPath = path.Replace(pathParam.Key, "0"); + path = string.Format(tempPath, pathParam.Value); + } + } + + var httpValues = HttpUtility.ParseQueryString(string.Empty); + foreach (var parameter in requestOptions.QueryParameters) + { +#if (NETCOREAPP) + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value); + } + } + else + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + } +#else + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(parameter.Key + "[]", value); + } + } + else + { + httpValues.Add(parameter.Key, parameter.Value[0]); + } +#endif + } + var uriBuilder = new UriBuilder(string.Concat(basePath, path)); + uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); + + var dateTime = DateTime.Now; + string Digest = string.Empty; + + //get the body + string requestBody = string.Empty; + if (requestOptions.Data != null) + { + var serializerSettings = new JsonSerializerSettings(); + requestBody = JsonConvert.SerializeObject(requestOptions.Data, serializerSettings); + } + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + { + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + } + + + foreach (var header in HttpSigningHeader) + { + if (header.Equals(HEADER_REQUEST_TARGET)) + { + var targetUrl = string.Format("{0} {1}{2}", method.ToLower(), uriBuilder.Path, uriBuilder.Query); + HttpSignatureHeader.Add(header.ToLower(), targetUrl); + } + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToString("r").ToString(); + HttpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host); + HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host); + } + else if (header.Equals(HEADER_CREATED)) + { + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + } + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest); + HttpSignatureHeader.Add(header.ToLower(), Digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in requestOptions.HeaderParameters) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + if (!isHeaderFound) + { + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + } + + } + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in HttpSignatureHeader) + { + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + + } + //Concatinate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm.ToString(), headerValuesString); + string headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + { + headerSignatureStr = GetRSASignature(signatureStringHash); + } + else if (keyType == PrivateKeyType.ECDSA) + { + headerSignatureStr = GetECDSASignature(signatureStringHash); + } + var cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (HttpSignatureHeader.ContainsKey(HEADER_CREATED)) + { + authorizationHeaderValue += string.Format(",created={0}", HttpSignatureHeader[HEADER_CREATED]); + } + + if (HttpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + { + authorizationHeaderValue += string.Format(",expires={0}", HttpSignatureHeader[HEADER_EXPIRES]); + } + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", + headersKeysString, headerSignatureStr); + + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(string hashName, string stringToBeHashed) + { + var hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName); + var bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + var stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + RSA rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + return string.Empty; + } + + /// + /// Gets the ECDSA signature + /// + /// + /// + private string GetECDSASignature(byte[] dataToSign) + { + if (!File.Exists(KeyFilePath)) + { + throw new Exception("key file path does not exist."); + } + + var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var keyStr = File.ReadAllText(KeyFilePath); + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + +#if (NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0) + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + { + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + } + else + { + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + } + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; +#else + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); +#endif + + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default lenght for ECDSA code signinged bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + { + rBytes.Add(signedBytes[i]); + } + for (int i = 32; i < 64; i++) + { + sBytes.Add(signedBytes[i]); + } + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r lenth, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) + { + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[] pemkey = null; + + if (!File.Exists(pemfile)) + { + throw new Exception("private key file does not exist."); + } + string pemstr = File.ReadAllText(pemfile).Trim(); + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + { + isPrivateKeyFile = false; + } + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPharse); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) + { + const string pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const string pemprivfooter = "-----END RSA PRIVATE KEY-----"; + string pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + { + return null; + } + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + string pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { + return null; + } + string saltline = str.ReadLine(); + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { + return null; + } + string saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + if (!(str.ReadLine() == "")) + { + return null; + } + + //------ remaining b64 data is encrypted RSA key ---- + string encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 fromat + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPharse, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + { + return null; + } + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + return rsakey; + } + } + + private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { + binr.ReadByte(); //advance 1 byte + } + else if (twobytes == 0x8230) + { + binr.ReadInt16(); //advance 2 bytes + } + else + { + return null; + } + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + { + return null; + } + bt = binr.ReadByte(); + if (bt != 0x00) + { + return null; + } + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + { + return 0; + } + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + while (binr.ReadByte() == 0x00) + { + //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store contatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- contatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and contatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + { + result = data00; //initialize + } + else + { + Array.Copy(result, hashtarget, result.Length); + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + result = md5.ComputeHash(result); + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //contatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result, 0, result.Length); + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// + private PrivateKeyType GetKeyType(string keyFilePath) + { + if (!File.Exists(keyFilePath)) + { + throw new Exception("Key file path does not exist."); + } + + var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + var ecPrivateKeyFooter = "END EC PRIVATE KEY"; + var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + var rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + var keyType = PrivateKeyType.None; + var key = File.ReadAllLines(keyFilePath); + + if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + { + keyType = PrivateKeyType.RSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + keyType = PrivateKeyType.ECDSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + + /* this type of key can hold many type different types of private key, but here due lack of pem header + Considering this as EC key + */ + //TODO :- update the key based on oid + keyType = PrivateKeyType.ECDSA; + } + else + { + throw new Exception("Either the key is invalid or key is not supported"); + + } + return keyType; + } + #endregion + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache new file mode 100644 index 00000000000..a269f56e904 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache @@ -0,0 +1,29 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + {{>visibility}} interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache new file mode 100644 index 00000000000..f0c88fae473 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache @@ -0,0 +1,92 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache new file mode 100644 index 00000000000..7c6487d92f8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache @@ -0,0 +1,114 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography.X509Certificates; + +namespace {{packageName}}.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time foramt. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + {{#hasHttpSignatureMethods}} + + /// + /// Gets the HttpSigning configuration + /// + HttpSigningConfiguration HttpSigningConfiguration { get; } + {{/hasHttpSignatureMethods}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache new file mode 100644 index 00000000000..c09bfbfed66 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache @@ -0,0 +1,85 @@ +{{>partial_header}} + +using System; +using System.IO; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache new file mode 100644 index 00000000000..9b1f66624d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache @@ -0,0 +1,125 @@ +{{>partial_header}} + +using System.Collections.Generic; +using System.Linq; +using JsonSubTypes; +using Newtonsoft.Json; +using NUnit.Framework; + +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.Client; + +namespace {{packageName}}.Test.Client +{ + public class JsonSubTypesTests + { + [Test] + public void TestSimpleJsonSubTypesExample() + { + var annimal = + JsonConvert.DeserializeObject("{\"Kind\":\"Dog\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (annimal as Dog)?.Breed); + } + + [Test] + public void DeserializeObjectWithCustomMapping() + { + var annimal = + JsonConvert.DeserializeObject("{\"Sound\":\"Bark\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (annimal as Dog2)?.Breed); + } + + [Test] + public void DeserializeObjectMappingByPropertyPresence() + { + string json = + "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]"; + + + var persons = JsonConvert.DeserializeObject>(json); + Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill); + } + } + + [JsonConverter(typeof(JsonSubtypes), "Kind")] + public interface IAnimal + { + string Kind { get; } + } + + public class Dog : IAnimal + { + public Dog() + { + Kind = "Dog"; + } + + public string Kind { get; } + public string Breed { get; set; } + } + + class Cat : IAnimal + { + public Cat() + { + Kind = "Cat"; + } + + public string Kind { get; } + bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes), "Sound")] + [JsonSubtypes.KnownSubType(typeof(Dog2), "Bark")] + [JsonSubtypes.KnownSubType(typeof(Cat2), "Meow")] + public class Animal2 + { + public virtual string Sound { get; } + public string Color { get; set; } + } + + public class Dog2 : Animal2 + { + public Dog2() + { + Sound = "Bark"; + } + + public override string Sound { get; } + public string Breed { get; set; } + } + + public class Cat2 : Animal2 + { + public Cat2() + { + Sound = "Meow"; + } + + public override string Sound { get; } + public bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes))] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")] + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + } + + public class Employee : Person + { + public string Department { get; set; } + public string JobTitle { get; set; } + } + + public class Artist : Person + { + public string Skill { get; set; } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache new file mode 100644 index 00000000000..8624af00924 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache @@ -0,0 +1,287 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache new file mode 100644 index 00000000000..d7905102576 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache @@ -0,0 +1,21 @@ +{{>partial_header}} +using Newtonsoft.Json.Converters; + +namespace {{packageName}}.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache new file mode 100644 index 00000000000..b15d2a25bf1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache @@ -0,0 +1,270 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Frameworks supported +{{#netStandard}} +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext +{{/netStandard}} + + +## Dependencies + +{{#useRestSharp}} +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later +{{/useRestSharp}} +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +{{#useCompareNetObjects}} +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +{{/useCompareNetObjects}} +{{#validatable}} +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later +{{/validatable}} + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +{{#useRestSharp}} +Install-Package RestSharp +{{/useRestSharp}} +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +{{#validatable}} +Install-Package System.ComponentModel.Annotations +{{/validatable}} +{{#useCompareNetObjects}} +Install-Package CompareNETObjects +{{/useCompareNetObjects}} +``` +{{#useRestSharp}} + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + +{{/useRestSharp}} + +## Installation +{{#netStandard}} +Generate the DLL using your preferred tool (e.g. `dotnet build`) +{{/netStandard}} +{{^netStandard}} +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` +{{/netStandard}} + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; +``` +{{^netStandard}} + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out {{packageName}}.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + +{{/netStandard}} + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` +{{#useHttpClient}} + +### Connections +Each ApiClass (properly the ApiClient inside it) will create an istance of HttpClient. It will use that for the entire lifecycle and dispose it when called the Dispose method. + +To better manager the connections it's a common practice to reuse the HttpClient and HttpClientHander (see [here](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net) for details). To use your own HttpClient instance just pass it to the ApiClass constructor. + +```csharp +HttpClientHandler yourHandler = new HttpClientHandler(); +HttpClient yourHttpClient = new HttpClient(yourHandler); +var api = new YourApiClass(yourHttpClient, yourHandler); +``` + +If you want to use an HttpClient and don't have access to the handler, for example in a DI context in Asp.net Core when using IHttpClientFactory. + +```csharp +HttpClient yourHttpClient = new HttpClient(); +var api = new YourApiClass(yourHttpClient); +``` +You'll loose some configuration settings, the features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. You need to either manually handle those in your setup of the HttpClient or they won't be available. + +Here an example of DI setup in a sample web project: + +```csharp +services.AddHttpClient(httpClient => + new PetApi(httpClient)); +``` + +{{/useHttpClient}} + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: Bearer Authentication +{{/isBasicBearer}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache new file mode 100644 index 00000000000..1299b2436be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache @@ -0,0 +1,137 @@ +{{>partial_header}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace {{packageName}}.Client +{ + public class ReadOnlyDictionary : IDictionary + { + private IDictionary _dictionaryImplementation; + public IEnumerator> GetEnumerator() + { + return _dictionaryImplementation.GetEnumerator(); + } + + public ReadOnlyDictionary() + { + _dictionaryImplementation = new Dictionary(); + } + + public ReadOnlyDictionary(IDictionary dictionaryImplementation) + { + if (dictionaryImplementation == null) throw new ArgumentNullException("dictionaryImplementation"); + _dictionaryImplementation = dictionaryImplementation; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _dictionaryImplementation).GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public void Clear() + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool Contains(KeyValuePair item) + { + return _dictionaryImplementation.Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + _dictionaryImplementation.CopyTo(array, arrayIndex); + } + + public bool Remove(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public int Count + { + get { return _dictionaryImplementation.Count; } + } + + public bool IsReadOnly + { + get { return true; } + } + + public void Add(T key, K value) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool ContainsKey(T key) + { + return _dictionaryImplementation.ContainsKey(key); + } + + public bool Remove(T key) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool TryGetValue(T key, out K value) + { + return _dictionaryImplementation.TryGetValue(key, out value); + } + + public K this[T key] + { + get { return _dictionaryImplementation[key]; } + set + { + throw new ReadonlyOperationException("This instance is readonly."); + + } + } + + public ICollection Keys + { + get { return _dictionaryImplementation.Keys; } + } + + public ICollection Values + { + get { return _dictionaryImplementation.Values; } + } + } + + [Serializable] + public class ReadonlyOperationException : Exception + { + // + // For guidelines regarding the creation of new exception types, see + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp + // and + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp + // + + public ReadonlyOperationException() + { + } + + public ReadonlyOperationException(string message) : base(message) + { + } + + public ReadonlyOperationException(string message, Exception inner) : base(message, inner) + { + } + + protected ReadonlyOperationException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache new file mode 100644 index 00000000000..dc924c733c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache new file mode 100644 index 00000000000..29aa6092681 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache @@ -0,0 +1,39 @@ +using Polly; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} + +namespace {{packageName}}.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public class RetryConfiguration + { +{{#useRestSharp}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useRestSharp}} +{{#useHttpClient}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useHttpClient}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache new file mode 100644 index 00000000000..112cc3dc405 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio {{^netStandard}}2012{{/netStandard}}{{#netStandard}}14{{/netStandard}} +VisualStudioVersion = {{^netStandard}}12.0.0.0{{/netStandard}}{{#netStandard}}14.0.25420.1{{/netStandard}} +MinimumVisualStudioVersion = {{^netStandard}}10.0.0.1{{/netStandard}}{{#netStandard}}10.0.40219.1{{/netStandard}} +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" +EndProject +{{^excludeTests}}Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +{{/excludeTests}}Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU + {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU + {{packageGuid}}.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 + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache new file mode 100644 index 00000000000..b1a50ae778e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache @@ -0,0 +1,36 @@ + + + + + false + Properties + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false + 512 + + + + + + + + + {{packageGuid}} + {{packageName}} + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache new file mode 100644 index 00000000000..8175f0e5757 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache @@ -0,0 +1,44 @@ +{{>partial_header}} +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A URI builder + /// + class WebRequestPathBuilder + { + private string _baseUrl; + private string _path; + private string _query = "?"; + public WebRequestPathBuilder(string baseUrl, string path) + { + _baseUrl = baseUrl; + _path = path; + } + + public void AddPathParameters(Dictionary parameters) + { + foreach (var parameter in parameters) + { + _path = _path.Replace("{" + parameter.Key + "}", parameter.Value); + } + } + + public void AddQueryParameters(Multimap parameters) + { + foreach (var parameter in parameters) + { + foreach (var value in parameter.Value) + { + _query = _query + parameter.Key + "=" + value + "&"; + } + } + } + + public string GetFullUri() + { + return _baseUrl + _path + _query.Substring(0, _query.Length - 1); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache new file mode 100644 index 00000000000..8d84eecefb4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache @@ -0,0 +1,626 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{notes}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache new file mode 100644 index 00000000000..d12ee22ea38 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache @@ -0,0 +1,134 @@ +# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{{operationId}}}** +> {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.AddApiKey("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{#isContainer}}{{baseType}}{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache new file mode 100644 index 00000000000..02ca26b5f16 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache @@ -0,0 +1,73 @@ +{{>partial_header}} +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +using Xunit; + +using {{packageName}}.Client; +using {{packageName}}.{{apiPackage}}; +{{#hasImport}} +// uncomment below to import models +//using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.Test.Api +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class {{classname}}Tests : IDisposable + { + private {{classname}} instance; + + public {{classname}}Tests() + { + instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{operationId}}InstanceTest() + { + // TODO uncomment below to test 'IsType' {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}} + /// + [Fact] + public void {{operationId}}Test() + { + // TODO uncomment below to test the method and replace null with proper value + {{#allParams}} + //{{{dataType}}} {{paramName}} = null; + {{/allParams}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}} + //Assert.IsType<{{{returnType}}}>(response); + {{/returnType}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache new file mode 100644 index 00000000000..eb85fc2a85b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\{{{packageName}}}\{{{packageName}}}.csproj -o ../../output -c Release --no-build diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache new file mode 100644 index 00000000000..4709282dead --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache @@ -0,0 +1,28 @@ +{{>partial_header}} + +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; + +namespace {{packageName}}.{{apiPackage}} +{ {{#operations}} + public partial {{#classModifier}}{{classModifier}} {{/classModifier}}class {{classname}} + { {{#operation}} + [FunctionName("{{classname}}_{{operationId}}")] + public async Task _{{operationId}}([HttpTrigger(AuthorizationLevel.Anonymous, "{{httpMethod}}", Route = "{{{apiBasePath}}}{{{path}}}")]HttpRequest req, ExecutionContext context{{#allParams}}{{#isPathParam}}, {{>pathParam}}{{/isPathParam}}{{/allParams}}) + { + var method = this.GetType().GetMethod("{{operationId}}"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context{{#allParams}}{{#isPathParam}}, {{/isPathParam}}{{/allParams}} })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + {{/operation}} + } +} + {{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache new file mode 100644 index 00000000000..8b3f689c912 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache @@ -0,0 +1,58 @@ +#!/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 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +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 credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache new file mode 100644 index 00000000000..1ee53850b84 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache new file mode 100644 index 00000000000..e9c39ea9f6d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache @@ -0,0 +1,739 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^netStandard}} +using System.Web; +{{/netStandard}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +{{#useWebRequest}} +using System.Net.Http; +{{/useWebRequest}} +using System.Net.Http; +using System.Net.Http.Headers; +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} + +namespace {{packageName}}.Client +{ + /// + /// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public async Task Deserialize(HttpResponseMessage response) + { + var result = (T) await Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal async Task Deserialize(HttpResponseMessage response, Type type) + { + IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); + + if (type == typeof(byte[])) // return byte array + { + return await response.Content.ReadAsByteArrayAsync(); + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = await response.Content.ReadAsByteArrayAsync(); + if (headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + /// + /// The Dispose method will manage the HttpClient lifecycle when not passed by constructor. + /// + {{>visibility}} partial class ApiClient : IDisposable, ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + public ApiClient() : + this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) + { + } + + /// + /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); + _disposeClient = true; + _baseUrl = basePath; + } + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath, handler) + { + } + + /// + /// Initializes a new instance of the . + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + if(_disposeClient) { + _httpClient.Dispose(); + } + } + + /// Prepares multipart/form-data content + {{! TODO: Add handling of improper usage }} + HttpContent PrepareMultipartFormDataContent(RequestOptions options) + { + string boundary = "---------" + Guid.NewGuid().ToString().ToUpperInvariant(); + var multipartContent = new MultipartFormDataContent(boundary); + foreach (var formParameter in options.FormParameters) + { + multipartContent.Add(new StringContent(formParameter.Value), formParameter.Key); + } + + if (options.FileParameters != null && options.FileParameters.Count > 0) + { + foreach (var fileParam in options.FileParameters) + { + var content = new StreamContent(fileParam.Value.Content); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + multipartContent.Add(content, fileParam.Key, + fileParam.Value.Name); + } + } + return multipartContent; + } + + /// + /// Provides all logic for constructing a new HttpRequestMessage. + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the a HttpRequestMessage. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new HttpRequestMessage instance. + /// + private HttpRequestMessage NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path); + + builder.AddPathParameters(options.PathParameters); + + builder.AddQueryParameters(options.QueryParameters); + + HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); + + if (configuration.UserAgent != null) + { + request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent); + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.Headers.Add(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + // Todo make content headers actually content headers + request.Headers.TryAddWithoutValidation(headerParam.Key, value); + } + } + } + + List> contentList = new List>(); + + string contentType = null; + if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type")) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes.FirstOrDefault(); + } + + {{!// TODO Add error handling in case of improper usage}} + if (contentType == "multipart/form-data") + { + request.Content = PrepareMultipartFormDataContent(options); + } + else if (contentType == "application/x-www-form-urlencoded") + { + request.Content = new FormUrlEncodedContent(options.FormParameters); + } + else + { + if (options.Data != null) + { + if (options.Data is FileParameter fp) + { + contentType = contentType ?? "application/octet-stream"; + + var streamContent = new StreamContent(fp.Content); + streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + request.Content = streamContent; + } + else + { + var serializer = new CustomJsonCodec(SerializerSettings, configuration); + request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(), + "application/json"); + } + } + } + + + + // TODO provide an alternative that allows cookies per request instead of per API client + if (options.Cookies != null && options.Cookies.Count > 0) + { + request.Properties["CookieContainer"] = options.Cookies; + } + + return request; + } + + partial void InterceptRequest(HttpRequestMessage req); + partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); + + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + { + T result = (T) responseData; + string rawContent = await response.Content.ReadAsStringAsync(); + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ReasonPhrase, + Cookies = new List() + }; + + // process response headers, e.g. Access-Control-Allow-Methods + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + // process response content headers, e.g. Content-Type + if (response.Content.Headers != null) + { + foreach (var responseHeader in response.Content.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (_httpClientHandler != null && response != null) + { + try { + foreach (Cookie cookie in _httpClientHandler.CookieContainer.GetCookies(uri)) + { + transformed.Cookies.Add(cookie); + } + } + catch (PlatformNotSupportedException) {} + } + + return transformed; + } + + private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) + { + return ExecAsync(req, configuration).GetAwaiter().GetResult(); + } + + private async Task> ExecAsync(HttpRequestMessage req, + IReadableConfiguration configuration, + System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var deserializer = new CustomJsonCodec(SerializerSettings, configuration); + + var finalToken = cancellationToken; + + if (configuration.Timeout > 0) + { + var tokenSource = new CancellationTokenSource(configuration.Timeout); + finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; +{{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { +{{/supportsRetry}} + response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); +{{#supportsRetry}} + } +{{/supportsRetry}} + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync(); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri); + } + + {{#supportsAsync}} + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(new HttpMethod("PATCH"), path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(new HttpMethod("PATCH"), path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache new file mode 100644 index 00000000000..3fa243ed54f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache @@ -0,0 +1,54 @@ +{{>partial_header}} + +using System.IO; + +namespace {{packageName}}.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache new file mode 100644 index 00000000000..bc5a8e348b8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache new file mode 100644 index 00000000000..20ddfe96b98 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache @@ -0,0 +1,724 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{notes}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : IDisposable, {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// The target service's base path in URL format. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// An instance of Configuration. + /// + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// + /// An instance of HttpClient. + /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, {{packageName}}.Client.Configuration configuration, HttpClientHandler handler = null) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + /// + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + this.ApiClient?.Dispose(); + } + + /// + /// Holds the ApiClient if created + /// + public {{packageName}}.Client.ApiClient ApiClient { get; set; } = null; + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache new file mode 100644 index 00000000000..0de1e05e514 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache @@ -0,0 +1,48 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using FileParameter = {{packageName}}.Client.FileParameter; +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache new file mode 100644 index 00000000000..339a6d2f76b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache @@ -0,0 +1,47 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache new file mode 100644 index 00000000000..931f7646da8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache @@ -0,0 +1,227 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + this.IsNullable = true; + this.SchemaType= "anyOf"; + } + + {{/isNullable}} + {{#anyOf}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{{.}}}. + public {{classname}}({{{.}}} actualInstance) + { + this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}}; + } + + {{/anyOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#anyOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) + { + this._actualInstance = value; + } + {{/anyOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#anyOf}} {{{.}}}{{^-last}},{{/-last}}{{/anyOf}}"); + } + } + } + {{#anyOf}} + + /// + /// Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{{.}}} + public {{{.}}} Get{{{.}}}() + { + return ({{{.}}})this.ActualInstance; + } + {{/anyOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (jsonString == null) + { + return new{{classname}}; + } + {{#anyOf}} + + try + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/anyOf}} + + // no match found, throw an exception + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return this.ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache new file mode 100644 index 00000000000..39bcd2eddc1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache @@ -0,0 +1,30 @@ + /// + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + [JsonConverter(typeof(StringEnumConverter))] + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{{value}}} + /// + {{#isString}} + [EnumMember(Value = "{{{value}}}")] + {{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + + {{/enumVars}} + {{/allowableValues}} + }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache new file mode 100644 index 00000000000..6eb1a2359d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache @@ -0,0 +1,456 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [DataContract(Name = "{{{name}}}")] + {{#discriminator}} + [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")] + {{#mappedModels}} + [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] + {{/mappedModels}} + {{/discriminator}} + {{>visibility}} partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/isEnum}} + {{#isEnum}} + + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + {{#isReadOnly}} + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + + {{^isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/vars}} + {{#hasRequired}} + {{^hasOnlyReadOnly}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + {{^isAdditionalPropertiesTrue}} + protected {{classname}}() { } + {{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + protected {{classname}}() + { + this.AdditionalProperties = new Dictionary(); + } + {{/isAdditionalPropertiesTrue}} + {{/hasOnlyReadOnly}} + {{/hasRequired}} + /// + /// Initializes a new instance of the class. + /// + {{#readWriteVars}} + /// {{#description}}{{description}}{{/description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. + {{/readWriteVars}} + {{#hasOnlyReadOnly}} + [JsonConstructorAttribute] + {{/hasOnlyReadOnly}} + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{#defaultValue}}{{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default({{{datatypeWithEnum}}}){{/isDateTime}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{^-last}}, {{/-last}}{{/parentVars}}){{/parent}} + { + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{#required}} + {{^conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{^required}} + {{#defaultValue}} + {{^vendorExtensions.x-csharp-value-type}} + // use default value if no "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" provided + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? {{{defaultValue}}}; + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/defaultValue}} + {{^defaultValue}} + {{^conditionalSerialization}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} + {{#conditionalSerialization}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} + {{/defaultValue}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + this.AdditionalProperties = new Dictionary(); + {{/isAdditionalPropertiesTrue}} + } + + {{#vars}} + {{^isInherited}} + {{^isEnum}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// {{#description}} + /// {{description}}{{/description}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + + {{#isReadOnly}} + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + public {{{dataType}}} {{name}} { get; private set; } + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{^isReadOnly}} + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{{dataType}}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{{dataType}}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + {{/isAdditionalPropertiesTrue}} + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#parent}} + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + {{/parent}} + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + {{#isAdditionalPropertiesTrue}} + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + {{/isAdditionalPropertiesTrue}} + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public {{#parent}}{{^isArray}}{{^isMap}}override {{/isMap}}{{/isArray}}{{/parent}}{{^parent}}virtual {{/parent}}string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}} + (this.{{name}} != null && + this.{{name}}.Equals(input.{{name}})) + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + this.{{name}}.Equals(input.{{name}}) + {{/vendorExtensions.x-is-value-type}} + ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}this.{{name}} != null && + input.{{name}} != null && + {{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); + {{/isAdditionalPropertiesTrue}} + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + {{#parent}} + int hashCode = base.GetHashCode(); + {{/parent}} + {{^parent}} + int hashCode = 41; + {{/parent}} + {{#vars}} + {{^vendorExtensions.x-is-value-type}} + if (this.{{name}} != null) + hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + {{/vendorExtensions.x-is-value-type}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + if (this.AdditionalProperties != null) + hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + {{/isAdditionalPropertiesTrue}} + return hashCode; + } + } + +{{#validatable}} +{{#discriminator}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { +{{/discriminator}} +{{^discriminator}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { +{{/discriminator}} + {{#parent}} + {{^isArray}} + {{^isMap}} + foreach(var x in BaseValidate(validationContext)) yield return x; + {{/isMap}} + {{/isArray}} + {{/parent}} + {{#vars}} + {{#hasValidation}} + {{^isEnum}} + {{#maxLength}} + // {{{name}}} ({{{dataType}}}) maxLength + if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } + + {{/maxLength}} + {{#minLength}} + // {{{name}}} ({{{dataType}}}) minLength + if(this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } + + {{/minLength}} + {{#maximum}} + // {{{name}}} ({{{dataType}}}) maximum + if(this.{{{name}}} > ({{{dataType}}}){{maximum}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); + } + + {{/maximum}} + {{#minimum}} + // {{{name}}} ({{{dataType}}}) minimum + if(this.{{{name}}} < ({{{dataType}}}){{minimum}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); + } + + {{/minimum}} + {{#pattern}} + {{^isByteArray}} + // {{{name}}} ({{{dataType}}}) pattern + Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); + if (false == regex{{{name}}}.Match(this.{{{name}}}).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); + } + + {{/isByteArray}} + {{/pattern}} + {{/isEnum}} + {{/hasValidation}} + {{/vars}} + yield break; + } +{{/validatable}} + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache new file mode 100644 index 00000000000..d9e96dccdb3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache @@ -0,0 +1,26 @@ + {{^isContainer}} + /// + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{#isString}} + [JsonConverter(typeof(StringEnumConverter))] + {{/isString}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{{value}}} + /// + {{#isString}} + [EnumMember(Value = "{{{value}}}")] + {{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + + {{/enumVars}} + {{/allowableValues}} + } + {{/isContainer}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache new file mode 100644 index 00000000000..d2d6e28b3f9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache @@ -0,0 +1,264 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + {{/isNullable}} + {{#oneOf}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{{.}}}. + public {{classname}}({{{.}}} actualInstance) + { + this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}}; + } + + {{/oneOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#oneOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) + { + this._actualInstance = value; + } + {{/oneOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#oneOf}} {{{.}}}{{^-last}},{{/-last}}{{/oneOf}}"); + } + } + } + {{#oneOf}} + + /// + /// Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{{.}}} + public {{{.}}} Get{{{.}}}() + { + return ({{{.}}})this.ActualInstance; + } + {{/oneOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (jsonString == null) + { + return new{{classname}}; + } + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + + string discriminatorValue = JObject.Parse(jsonString)["{{{propertyBaseName}}}"].ToString(); + switch (discriminatorValue) + { + {{#mappedModels}} + case "{{{mappingName}}}": + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{modelName}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + return new{{classname}}; + {{/mappedModels}} + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + break; + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + List matchedTypes = new List(); + {{#oneOf}} + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof({{{.}}}).GetProperty("AdditionalProperties") == null) + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + } + else + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("{{{.}}}"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/oneOf}} + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return this.ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache new file mode 100644 index 00000000000..babf25481c4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache @@ -0,0 +1,22 @@ +{{#models}} +{{#model}} +# {{{packageName}}}.{{modelPackage}}.{{{classname}}} +{{#description}}{{&description}} +{{/description}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#parent}} +{{#parentVars}} +**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/parentVars}} +{{/parent}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache new file mode 100644 index 00000000000..b4aefe51005 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache @@ -0,0 +1,81 @@ +{{>partial_header}} + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.Client; +using System.Reflection; +using Newtonsoft.Json; + +{{#models}} +{{#model}} +namespace {{packageName}}.Test.Model +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class {{classname}}Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; + + public {{classname}}Tests() + { + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{classname}}InstanceTest() + { + // TODO uncomment below to test "IsType" {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + + {{#discriminator}} + {{#children}} + /// + /// Test deserialize a {{classname}} from type {{parent}} + /// + [Fact] + public void {{classname}}DeserializeFrom{{parent}}Test() + { + // TODO uncomment below to test deserialize a {{classname}} from type {{parent}} + //Assert.IsType<{{parent}}>(JsonConvert.DeserializeObject<{{parent}}>(new {{classname}}().ToJson())); + } + {{/children}} + {{/discriminator}} + + {{#vars}} + /// + /// Test the property '{{name}}' + /// + [Fact] + public void {{name}}Test() + { + // TODO unit test for the property '{{name}}' + } + {{/vars}} + + } + +} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache new file mode 100644 index 00000000000..4f29dcf3d34 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache @@ -0,0 +1,44 @@ + + + + false + {{targetFramework}} + {{packageName}} + {{packageName}} + Library + {{packageAuthors}} + {{packageCompany}} + {{packageTitle}} + {{packageDescription}} + {{packageCopyright}} + {{packageName}} + {{packageVersion}} + bin\$(Configuration)\$(TargetFramework)\{{packageName}}.xml{{#licenseId}} + {{licenseId}}{{/licenseId}} + https://{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}.git + git{{#releaseNote}} + {{releaseNote}}{{/releaseNote}}{{#packageTags}} + {{{packageTags}}}{{/packageTags}} + {{#nullableReferenceTypes}} + annotations + {{/nullableReferenceTypes}} + + + + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + + + {{#useRestSharp}} + + {{/useRestSharp}} + {{#supportsRetry}} + + {{/supportsRetry}} + {{#validatable}} + + {{/validatable}} + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache new file mode 100644 index 00000000000..b20a94c76c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache @@ -0,0 +1,20 @@ + + + + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false + + + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache new file mode 100644 index 00000000000..66254acffd4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache @@ -0,0 +1,52 @@ + + + + + $id$ + {{packageTitle}} + + + $version$ + + + $author$ + + + $author$ + false + false + + + {{packageDescription}} + {{#termsOfService}} + {{termsOfService}} + {{/termsOfService}} + {{#licenseUrl}} + {{licenseUrl}} + {{/licenseUrl}} + + + + + + + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + + {{#validatable}} + + {{/validatable}} + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache new file mode 100644 index 00000000000..755e937d23b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache @@ -0,0 +1,17 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + {{#version}} + * The version of the OpenAPI document: {{{version}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{infoEmail}}} + {{/infoEmail}} + * Generated by: https://github.com/openapitools/openapi-generator.git + */ diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache new file mode 100644 index 00000000000..e8767cac94c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache new file mode 100644 index 00000000000..d5d3017c216 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache @@ -0,0 +1,12 @@ +{ + "supports": {}, + "dependencies": { + "FubarCoder.RestSharp.Portable.Core": "4.0.7", + "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7", + "Newtonsoft.Json": "10.0.3", + "JsonSubTypes": "1.2.0" + }, + "frameworks": { + "netstandard1.3": {} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache new file mode 100644 index 00000000000..a1d1f4163d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache index e3cc6755362..0668b2e7b1d 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache @@ -11,7 +11,7 @@ class {{classname}} extends EnumClass { {{#description}} /// {{{.}}} {{/description}} - @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}}) + @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{#isLong}}wireNumber: {{{value}}}{{/isLong}}{{^isInteger}}{{^isLong}}wireName: r{{{value}}}{{/isLong}}{{/isInteger}}) static const {{classname}} {{name}} = _${{name}}; {{/enumVars}} {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache index 5f5dfd49913..c6452b7f6f5 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache @@ -5,7 +5,7 @@ class {{{enumName}}} extends EnumClass { {{#description}} /// {{{.}}} {{/description}} - @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}}) + @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{#isLong}}wireNumber: {{{value}}}{{/isLong}}{{^isInteger}}{{^isLong}}wireName: r{{{value}}}{{/isLong}}{{/isInteger}}) static const {{{enumName}}} {{name}} = _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}_{{name}}; {{/enumVars}} {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache index e1f3dbe1df5..c558f153c89 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache @@ -19,17 +19,17 @@ part 'serializers.g.dart'; @SerializersFor([{{#models}}{{#model}} {{classname}},{{/model}}{{/models}} ]) -Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#serializers}} +Serializers serializers = (_$serializers.toBuilder(){{#builtValueSerializers}} ..addBuilderFactory( {{#isArray}} - const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType({{baseType}})]), - () => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{baseType}}>(), + const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType{{#isNullable}}.nullable{{/isNullable}}({{dataType}})]), + () => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{dataType}}>(), {{/isArray}} {{#isMap}} - const FullType(BuiltMap, [FullType(String), FullType({{baseType}})]), - () => MapBuilder(), + const FullType(BuiltMap, [FullType(String), FullType{{#isNullable}}.nullable{{/isNullable}}({{dataType}})]), + () => MapBuilder(), {{/isMap}} - ){{/serializers}}{{/apis}}{{/apiInfo}}{{#useDateLibTimeMachine}} + ){{/builtValueSerializers}}{{#useDateLibTimeMachine}} ..add(const OffsetDateSerializer()) ..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}}{{#useDateLibCore}} ..add(const DateSerializer()) diff --git a/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache b/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache index a5ad68cc9c8..2f3f276c476 100644 --- a/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache +++ b/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache @@ -134,7 +134,7 @@ {{#responses}}

{{code}}

{{message}} - {{#simpleType}}{{dataType}}{{/simpleType}} + {{^containerType}}{{dataType}}{{/containerType}} {{#examples}}

Example data

Content-Type: {{{contentType}}}
diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache index 2a620721ba4..4a09e4daf46 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -93,4 +93,7 @@ tasks { } } } + register("test") { + dependsOn("allTests") + } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index 84836e45e7e..470c4bc2926 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -34,15 +34,20 @@ import {{packageName}}.auth.* KotlinxSerializer(json).ignoreOutgoingContent() } - private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { - val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - { it.install(JsonFeature, jsonConfig) } + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + // Hold a reference to the serializer to avoid freezing the entire ApiClient instance + // when the JsonFeature is configured. + val serializerReference = serializer + it.install(JsonFeature) { serializer = serializerReference } + httpClientConfig?.invoke(it) + } } private val client: HttpClient by lazy { - val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } + {{#hasAuthMethods}} private val authentications: kotlin.collections.Map by lazy { mapOf({{#authMethods}}{{#isBasic}}{{#isBasicBasic}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache index 0a5ecca3d6b..9435bf7f24a 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache @@ -19,7 +19,7 @@ This server has been generated with [Laminas (Zend) PSR-7 implementation](https: ## Requirements * Web server with URL rewriting -* PHP 7.3 or newer +* PHP 7.4 or newer This package contains `.htaccess` for Apache configuration. If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc. diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache index 4375a02d56a..803a0c140cd 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache @@ -8,7 +8,7 @@ } ], "require": { - "php": "^7.3 || ^8.0", + "php": "^7.4 || ^8.0", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", "ybelenko/openapi-data-mocker": "^1.0", diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache index b3278a2920e..8a61a5402ff 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache @@ -2,7 +2,7 @@ {{#appName}} * {{{.}}} {{/appName}} - * PHP version 7.3 + * PHP version 7.4 * * @package {{invokerPackage}} * @author OpenAPI Generator team diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index 3b2c5eafce1..1195d5ea9c4 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index 6e95e653a32..42b44955aad 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -57,7 +57,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @discardableResult - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) -> URLSessionTask? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) -> URLSessionTask? { return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { {{#returnType}} @@ -91,7 +91,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { let deferred = Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}>.pending() {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { @@ -122,7 +122,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { return Observable.create { observer -> Disposable in let task = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { @@ -160,7 +160,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { var task: URLSessionTask? return Future<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { promise in task = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in @@ -198,7 +198,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) async throws{{#returnType}} -> {{{returnType}}}{{/returnType}} { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) async throws{{#returnType}} -> {{{returnType}}}{{/returnType}} { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -241,7 +241,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @discardableResult - open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{{returnType}}}{{^returnType}}Void{{/returnType}}, ErrorResponse>) -> Void)) -> URLSessionTask? { + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{{returnType}}}{{^returnType}}Void{{/returnType}}, ErrorResponse>) -> Void)) -> URLSessionTask? { return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { {{#returnType}} @@ -411,7 +411,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}} let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})" let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" diff --git a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache index 7d7c58f1dc4..7faccc1a1d8 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache @@ -15,18 +15,18 @@ Method | HTTP request | Description {{^usePromiseKit}} {{^useRxSwift}} {{^useVapor}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) {{/useVapor}} {{/useRxSwift}} {{/usePromiseKit}} {{#usePromiseKit}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> {{/usePromiseKit}} {{#useRxSwift}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> {{/useRxSwift}} {{#useVapor}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> {{/useVapor}} ``` diff --git a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache index 4d868682a1e..08f7bf9ee40 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache @@ -1,7 +1,32 @@ -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable{{^generateFrozenEnums}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{/generateFrozenEnums}} { {{#allowableValues}} {{#enumVars}} case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} +{{^generateFrozenEnums}} + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. +{{#isString}} + case unknownDefaultOpenAPI = "unknown_default_open_api" +{{/isString}} +{{#isNumeric}} + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // +{{/isNumeric}} +{{#isInteger}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isInteger}} +{{#isDouble}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isDouble}} +{{#isFloat}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isFloat}} +{{/generateFrozenEnums}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache index 039bae3cb73..1dd9c55b16f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache @@ -1,7 +1,35 @@ - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable{{^generateFrozenEnums}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{#isContainer}}, CaseIterableDefaultsLast{{/isContainer}}{{/generateFrozenEnums}} { {{#allowableValues}} {{#enumVars}} case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} + {{^generateFrozenEnums}} + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + {{#isString}} + case unknownDefaultOpenAPI = "unknown_default_open_api" + {{/isString}} + {{#isContainer}} + case unknownDefaultOpenAPI = "unknown_default_open_api" + {{/isContainer}} + {{#isNumeric}} + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + {{/isNumeric}} + {{#isInteger}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isInteger}} + {{#isDouble}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isDouble}} + {{#isFloat}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isFloat}} + {{/generateFrozenEnums}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache index fae34faa975..1c16a3955bc 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache @@ -1,4 +1,4 @@ -public enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}} { +public enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}}{{/useVapor}} { {{#oneOf}} case type{{.}}({{.}}) {{/oneOf}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 28748850f1b..949bc1a9243 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -3877,6 +3877,59 @@ public class DefaultCodegenTest { } @Test + public void testResponses() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/response-tests.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + codegen.setDisallowAdditionalPropertiesIfNotPresent(false); + + String path; + Operation operation; + CodegenOperation co; + CodegenParameter cpa; + CodegenResponse cr; + + path = "/pet/{petId}"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + //assertTrue(co.hasErrorResponseObject); + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + cr = co.responses.get(3); + assertTrue(cr.is5xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + path = "/pet"; + operation = openAPI.getPaths().get(path).getPut(); + co = codegen.fromOperation(path, "PUT", operation, null); + assertTrue(co.hasErrorResponseObject); + + // 200 response + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + // 400 response + cr = co.responses.get(1); + assertTrue(cr.is4xx); + assertEquals(cr.code, "400"); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + path = "/pet/findByTags"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertFalse(co.hasErrorResponseObject); + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + } + public void testParameterContent() { DefaultCodegen codegen = new DefaultCodegen(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/content-data.yaml"); @@ -3922,11 +3975,13 @@ public class DefaultCodegenTest { CodegenMediaType mt = content.get("application/json"); assertNull(mt.getEncoding()); CodegenProperty cp = mt.getSchema(); + assertEquals(cp.baseName, "ApplicationJsonSchema"); assertNotNull(cp); mt = content.get("text/plain"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "TextPlainSchema"); assertNotNull(cp); // Note: the inline model resolver has a bug for this use case; it extracts an inline request body into a component // but the schema it references is not string type @@ -3940,11 +3995,13 @@ public class DefaultCodegenTest { mt = content.get("application/json"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "ApplicationJsonSchema"); assertEquals(cp.complexType, "coordinates"); mt = content.get("text/plain"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "TextPlainSchema"); assertTrue(cp.isString); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java new file mode 100644 index 00000000000..a62b73e7fae --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2020 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.CsharpNetcoreFunctionsServerCodegen; + +import org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class CsharpNetcoreFunctionsServerCodegenTest { + + @Test + public void testToEnumVarName() throws Exception { + final CsharpNetcoreFunctionsServerCodegen codegen = new CsharpNetcoreFunctionsServerCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.toEnumVarName("FooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("fooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo-bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo_bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo bar", "string"), "FooBar"); + + // The below cases do not work currently, camelize doesn't support uppercase + // Assert.assertEquals(codegen.toEnumVarName("FOO-BAR", "string"), "FooBar"); + // Assert.assertEquals(codegen.toEnumVarName("FOO_BAR", "string"), "FooBar"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java index cf6b8ba3bfa..4df5b89d5ba 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java @@ -48,6 +48,7 @@ public class Swift5OptionsProvider implements OptionsProvider { public static final String REMOVE_MIGRATION_PROJECT_NAME_CLASS_VALUE = "false"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; public static final String USE_BACKTICKS_ESCAPES_VALUE = "false"; + public static final String GENERATE_FROZEN_ENUMS_VALUE = "true"; public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE = "true"; public static final String HASHABLE_MODELS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @@ -95,6 +96,7 @@ public class Swift5OptionsProvider implements OptionsProvider { .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") .put(Swift5ClientCodegen.USE_SPM_FILE_STRUCTURE, USE_SPM_FILE_STRUCTURE_VALUE) .put(Swift5ClientCodegen.SWIFT_PACKAGE_PATH, SWIFT_PACKAGE_PATH_VALUE) + .put(Swift5ClientCodegen.GENERATE_FROZEN_ENUMS, GENERATE_FROZEN_ENUMS_VALUE) .put(Swift5ClientCodegen.GENERATE_MODEL_ADDITIONAL_PROPERTIES, GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE) .put(Swift5ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE) .put(Swift5ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java index 15a06885bc0..0550f03de29 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java @@ -49,6 +49,7 @@ public class Swift5OptionsTest extends AbstractOptionsTest { verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(Swift5OptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setReadonlyProperties(Boolean.parseBoolean(Swift5OptionsProvider.READONLY_PROPERTIES_VALUE)); verify(clientCodegen).setRemoveMigrationProjectNameClass(Boolean.parseBoolean(Swift5OptionsProvider.REMOVE_MIGRATION_PROJECT_NAME_CLASS_VALUE)); + verify(clientCodegen).setGenerateFrozenEnums(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_FROZEN_ENUMS_VALUE)); verify(clientCodegen).setGenerateModelAdditionalProperties(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE)); verify(clientCodegen).setHashableModels(Boolean.parseBoolean(Swift5OptionsProvider.HASHABLE_MODELS_VALUE)); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index e5a76bd02a3..61231472997 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -8,14 +8,18 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + public class TypeScriptAngularClientCodegenTest { @Test @@ -267,4 +271,44 @@ public class TypeScriptAngularClientCodegenTest { codegen.importMapping().put(importedModel, importName); Assert.assertEquals(codegen.toModelImport(importedModel), importName); } + + @Test + public void testTaggedUnionImports() throws Exception { + final String specPath = "src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml"; + + Map properties = new HashMap<>(); + properties.put(TypeScriptAngularClientCodegen.TAGGED_UNIONS, "true"); + + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-angular") + .setInputSpec(specPath) + .setAdditionalProperties(properties) + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + + Generator generator = new DefaultGenerator(); + generator.opts(clientOptInput).generate(); + + TestUtils.assertFileContains( + Paths.get(output + "/model/expressionToken.ts"), + "import { Token } from './token'", // imports the parent schema + "import { TokenMetadata } from './tokenMetadata'", // imports a schema referenced in an inherited property + "export interface ExpressionToken {" // no inheritance + ); + + TestUtils.assertFileNotContains( + Paths.get(output + "/model/stringToken.ts"), + "import { Token } from './token'" + ); + + TestUtils.assertFileContains( + Paths.get(output + "/model/token.ts"), + "import { ExpressionToken } from './expressionToken'", + "export type Token = ExpressionToken | StringToken" + ); + } } diff --git a/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml b/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml new file mode 100644 index 00000000000..de3b9f21177 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml @@ -0,0 +1,51 @@ +openapi: 3.0.2 +info: + title: OAI Specification example for Polymorphism + version: 1.0.0 +paths: + /status: + get: + responses: + '201': + description: desc + +components: + schemas: + TokenMetadata: + type: object + properties: + tag1: + type: string + + Token: + type: object + required: + - type + properties: + type: + type: string + metadata: + $ref: '#/components/schemas/TokenMetadata' + discriminator: + propertyName: type + mapping: + string: '#/components/schemas/StringToken' + expression: '#/components/schemas/ExpressionToken' + + StringToken: + allOf: + - $ref: '#/components/schemas/Token' + - type: object + properties: + value: + type: string + + ExpressionToken: + allOf: + - $ref: '#/components/schemas/Token' + - type: object + properties: + tokens: + type: array + items: + $ref: '#/components/schemas/Token' \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml b/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml new file mode 100644 index 00000000000..e17881606db --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml @@ -0,0 +1,571 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '500': + description: Server error + content: + application/application: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + '500': + description: Server error + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/openapi-generator.code-workspace b/openapi-generator.code-workspace new file mode 100644 index 00000000000..94b0864b5d8 --- /dev/null +++ b/openapi-generator.code-workspace @@ -0,0 +1,78 @@ +{ + "folders": [ + { + "name": "openapi-generator", + "path": "." + }, + { + "name": "openapi-generator-cli", + "path": "modules/openapi-generator-cli" + }, + { + "name": "openapi-generator-core", + "path": "modules/openapi-generator-core" + }, + { + "name": "openapi-generator-gradle-plugin", + "path": "modules/openapi-generator-gradle-plugin" + }, + { + "name": "openapi-generator-maven-plugin", + "path": "modules/openapi-generator-maven-plugin" + }, + { + "name": "openapi-generator-online", + "path": "modules/openapi-generator-online" + }, + ], + "settings": { + "editor.formatOnType": true, + "editor.linkedEditing": true, + "editor.tabCompletion": "on", + "editor.tabSize": 4, + "editor.renderWhitespace": "boundary", + "editor.suggest.shareSuggestSelections": true, + "editor.suggestSelection": "first", + "editor.semanticHighlighting.enabled": true, + "explorer.confirmDelete": true, + + "files.autoSave": "onFocusChange", + "files.exclude": { + "**/.classpath": true, + "**/.factorypath": true, + "**/.project": true, + "**/.settings": true + }, + "files.trimFinalNewlines": false, + "files.trimTrailingWhitespace": true, + + "task.saveBeforeRun": "always", + + "java.autobuild.enabled": false, + "java.completion.enabled": true, + "java.completion.guessMethodArguments": true, + "java.completion.maxResults": 5, + "java.format.onType.enabled": true, + + "java.referencesCodeLens.enabled": true, + "java.saveActions.organizeImports": true, + "java.showBuildStatusOnStart.enabled": true, + + "java.dependency.autoRefresh": true, + "java.dependency.refreshDelay": 3000, + "java.format.enabled": true, + + "maven.pomfile.autoUpdateEffectivePOM": true, + }, + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "attilabuti.mustache-syntax-vscode", + "formulahendry.code-runner", + "visualstudioexptteam.vscodeintellicode", + "42crunch.vscode-openapi", + "mermade.openapi-lint" + + ] + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index bc359854717..d55abd2e50d 100644 --- a/pom.xml +++ b/pom.xml @@ -1434,6 +1434,7 @@ samples/client/petstore/swift5/combineLibrary samples/client/petstore/swift5/default samples/client/petstore/swift5/deprecated + samples/client/petstore/swift5/frozenEnums samples/client/petstore/swift5/nonPublicApi samples/client/petstore/swift5/objcCompatible samples/client/petstore/swift5/promisekitLibrary diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java index 53717e8ac51..40146a3e6f5 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java @@ -221,7 +221,6 @@ public class JSON { .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) .registerTypeAdapter(byte[].class, byteArrayAdapter) .registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory()) - .registerTypeAdapterFactory(new org.openapitools.client.model.Animal.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.Apple.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.AppleReq.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfArrayOfNumberOnly.CustomTypeAdapterFactory()) @@ -251,7 +250,6 @@ public class JSON { .registerTypeAdapterFactory(new org.openapitools.client.model.Fruit.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.FruitReq.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.GmFruit.CustomTypeAdapterFactory()) - .registerTypeAdapterFactory(new org.openapitools.client.model.GrandparentAnimal.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.HasOnlyReadOnly.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.HealthCheckResult.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.InlineResponseDefault.CustomTypeAdapterFactory()) diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java index cf1f00de64f..4d60101ca17 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java @@ -144,60 +144,4 @@ public class Animal { return o.toString().replace("\n", "\n "); } - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("className"); - openapiFields.add("color"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("className"); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Animal.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Animal' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Animal.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Animal value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Animal read(JsonReader in) throws IOException { - JsonObject obj = elementAdapter.read(in).getAsJsonObject(); - Set> entries = obj.entrySet();//will return members of your object - // check to see if the JSON string contains additional fields - for (Entry entry: entries) { - if (!Animal.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Animal` properties"); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Animal.openapiRequiredFields) { - if (obj.get(requiredField) == null) { - throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); - } - } - - return thisAdapter.fromJsonTree(obj); - } - - }.nullSafe(); - } - } } diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java index df924fe5f33..085ccbfbfc1 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -114,59 +114,4 @@ public class GrandparentAnimal { return o.toString().replace("\n", "\n "); } - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("pet_type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("pet_type"); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!GrandparentAnimal.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'GrandparentAnimal' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(GrandparentAnimal.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, GrandparentAnimal value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public GrandparentAnimal read(JsonReader in) throws IOException { - JsonObject obj = elementAdapter.read(in).getAsJsonObject(); - Set> entries = obj.entrySet();//will return members of your object - // check to see if the JSON string contains additional fields - for (Entry entry: entries) { - if (!GrandparentAnimal.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `GrandparentAnimal` properties"); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : GrandparentAnimal.openapiRequiredFields) { - if (obj.get(requiredField) == null) { - throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); - } - } - - return thisAdapter.fromJsonTree(obj); - } - - }.nullSafe(); - } - } } diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts index 2c891e8fa4f..eb33cf023bf 100644 --- a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts @@ -93,4 +93,7 @@ tasks { } } } + register("test") { + dependsOn("allTests") + } } diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4fbb14f3f45..a6ec2640afc 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -34,15 +34,20 @@ open class ApiClient( KotlinxSerializer(json).ignoreOutgoingContent() } - private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { - val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - { it.install(JsonFeature, jsonConfig) } + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + // Hold a reference to the serializer to avoid freezing the entire ApiClient instance + // when the JsonFeature is configured. + val serializerReference = serializer + it.install(JsonFeature) { serializer = serializerReference } + httpClientConfig?.invoke(it) + } } private val client: HttpClient by lazy { - val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } + private val authentications: kotlin.collections.Map by lazy { mapOf( "api_key" to ApiKeyAuth("header", "api_key"), diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e773584bb02..8e449d22dc7 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -589,7 +589,7 @@ open class FakeAPI { - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -627,7 +627,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 2f713417bfb..f169ed382da 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -152,7 +152,7 @@ open class PetAPI { - returns: [Pet] */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> [Pet] { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> [Pet] { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -186,7 +186,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b64f5581ea6..27b455e59ff 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -561,7 +561,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { var task: URLSessionTask? return Future { promise in task = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in @@ -594,7 +594,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1335065e013..71225a5b53d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -148,7 +148,7 @@ open class PetAPI { */ #if canImport(Combine) @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { var task: URLSessionTask? return Future<[Pet], Error> { promise in task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in @@ -177,7 +177,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index faaa1611c8f..bf154f2e1db 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -529,7 +529,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -554,7 +554,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 87aedd5c1a3..655b2358c52 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/default/docs/FakeAPI.md b/samples/client/petstore/swift5/default/docs/FakeAPI.md index e2df98a9d44..5004221689e 100644 --- a/samples/client/petstore/swift5/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/default/docs/FakeAPI.md @@ -492,7 +492,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/default/docs/PetAPI.md b/samples/client/petstore/swift5/default/docs/PetAPI.md index 6195924f3c2..ee837e6f8af 100644 --- a/samples/client/petstore/swift5/default/docs/PetAPI.md +++ b/samples/client/petstore/swift5/default/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f838ced0df6..59a82575aa1 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/deprecated/docs/PetAPI.md b/samples/client/petstore/swift5/deprecated/docs/PetAPI.md index c602c9fb572..cd138421072 100644 --- a/samples/client/petstore/swift5/deprecated/docs/PetAPI.md +++ b/samples/client/petstore/swift5/deprecated/docs/PetAPI.md @@ -114,7 +114,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/frozenEnums/.gitignore b/samples/client/petstore/swift5/frozenEnums/.gitignore new file mode 100644 index 00000000000..627d360a903 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.gitignore @@ -0,0 +1,105 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore b/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES new file mode 100644 index 00000000000..c81943baf2a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES @@ -0,0 +1,110 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/Category.swift +PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +PetstoreClient/Classes/OpenAPIs/Models/Client.swift +PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +PetstoreClient/Classes/OpenAPIs/Models/File.swift +PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/List.swift +PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +PetstoreClient/Classes/OpenAPIs/Models/Name.swift +PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/Order.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +PetstoreClient/Classes/OpenAPIs/Models/Return.swift +PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeAPI.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeAPI.md +docs/FakeClassnameTags123API.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetAPI.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md +docs/StoreAPI.md +docs/StringBooleanMap.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserAPI.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/frozenEnums/Cartfile b/samples/client/petstore/swift5/frozenEnums/Cartfile new file mode 100644 index 00000000000..3f7e6304cab --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Cartfile @@ -0,0 +1 @@ +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/frozenEnums/Package.resolved b/samples/client/petstore/swift5/frozenEnums/Package.resolved new file mode 100644 index 00000000000..730957420e1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "b1a7a8a6186f2fcb28f7bda67cfc545de48b3c80", + "version": "0.6.2" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/frozenEnums/Package.swift b/samples/client/petstore/swift5/frozenEnums/Package.swift new file mode 100644 index 00000000000..87bb775fb72 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec b/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec new file mode 100644 index 00000000000..0e6bf7ec024 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '1.0.0' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' +end diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift new file mode 100644 index 00000000000..049b7f655f1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -0,0 +1,86 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") + } + return source + } + + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift new file mode 100644 index 00000000000..a7933c418ad --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -0,0 +1,72 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// We reverted the change of PetstoreClientAPI to PetstoreClient introduced in https://github.com/OpenAPITools/openapi-generator/pull/9624 +// Because it was causing the following issue https://github.com/OpenAPITools/openapi-generator/issues/9953 +// If you are affected by this issue, please consider removing the following two lines, +// By setting the option removeMigrationProjectNameClass to true in the generator +@available(*, deprecated, renamed: "PetstoreClientAPI") +public typealias PetstoreClient = PetstoreClientAPI + +open class PetstoreClientAPI { + public static var basePath = "http://petstore.swagger.io:80/v2" + public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? + public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. + /// If you need to get the request's progress in older OS versions, please use Alamofire http client. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + @discardableResult + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> URLSessionTask? { + return nil + } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift new file mode 100644 index 00000000000..ac45c1f454b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -0,0 +1,58 @@ +// +// AnotherFakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class AnotherFakeAPI { + + /** + To test special tags + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test special tags + - PATCH /another-fake/dummy + - To test special tags and operation ID starting with number + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift new file mode 100644 index 00000000000..9f5c7a495e1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -0,0 +1,699 @@ +// +// FakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeAPI { + + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - parameter body: (body) Input boolean as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - parameter body: (body) Input composite as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - parameter body: (body) Input number as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - parameter body: (body) Input string as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-file-schema + - For this test, the body for this request much reference a schema named `File`. + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter query: (query) + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-query-params + - parameter query: (query) + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "query": query.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter number: (form) None + - parameter float: (form) None (optional) + - parameter double: (form) None + - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testEndpointParametersWithRequestBuilder(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: http + - name: http_basic_test + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter number: (form) None + - parameter float: (form) None (optional) + - parameter double: (form) None + - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number.encodeToJSON(), + "float": float?.encodeToJSON(), + "double": double.encodeToJSON(), + "string": string?.encodeToJSON(), + "pattern_without_delimiter": patternWithoutDelimiter.encodeToJSON(), + "byte": byte.encodeToJSON(), + "binary": binary?.encodeToJSON(), + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password?.encodeToJSON(), + "callback": callback?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int, CaseIterable { + case _1 = 1 + case number2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double, CaseIterable { + case _11 = 1.1 + case number12 = -1.2 + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + To test enum parameters + + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test enum parameters + - GET /fake + - To test enum parameters + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "enum_form_string_array": enumFormStringArray?.encodeToJSON(), + "enum_form_string": enumFormString?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_double": enumQueryDouble?.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), + "enum_header_string": enumHeaderString?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Fake endpoint to test group parameters (optional) + + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint to test group parameters (optional) + - DELETE /fake + - Fake endpoint to test group parameters (optional) + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - returns: RequestBuilder + */ + open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), + "int64_group": int64Group?.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + "required_boolean_group": requiredBooleanGroup.encodeToJSON(), + "boolean_group": booleanGroup?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + test inline additionalProperties + + - parameter param: (body) request body + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test inline additionalProperties + - POST /fake/inline-additionalProperties + - parameter param: (body) request body + - returns: RequestBuilder + */ + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + test json serialization of form data + + - parameter param: (form) field1 + - parameter param2: (form) field2 + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test json serialization of form data + - GET /fake/jsonFormData + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: RequestBuilder + */ + open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "param": param.encodeToJSON(), + "param2": param2.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift new file mode 100644 index 00000000000..ac274a7c550 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -0,0 +1,61 @@ +// +// FakeClassnameTags123API.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeClassnameTags123API { + + /** + To test class name in snake case + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test class name in snake case + - PATCH /fake_classname_test + - To test class name in snake case + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift new file mode 100644 index 00000000000..2baca7e644a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -0,0 +1,495 @@ +// +// PetAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class PetAPI { + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Add a new pet to the store + - POST /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Deletes a pet + + - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deletePetWithRequestBuilder(apiKey: apiKey, petId: petId).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(apiKey: String? = nil, petId: Int64) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "api_key": apiKey?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String, CaseIterable { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter status: (query) Status values that need to be considered for filter + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "status": status.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @available(*, deprecated, message: "This operation is deprecated.") + @discardableResult + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter tags: (query) Tags to filter by + - returns: RequestBuilder<[Pet]> + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "tags": tags.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - parameter petId: (path) ID of pet to return + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Update an existing pet + - PUT /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: RequestBuilder + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "name": name?.encodeToJSON(), + "status": status?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) -> URLSessionTask? { + return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: RequestBuilder + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var localVariablePath = "/pet/{petId}/uploadImage" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "file": file?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + uploads an image (required) + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) -> URLSessionTask? { + return uploadFileWithRequiredFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image (required) + - POST /fake/{petId}/uploadImageWithRequiredFile + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload + - returns: RequestBuilder + */ + open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL) -> RequestBuilder { + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "requiredFile": requiredFile.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift new file mode 100644 index 00000000000..f2539226866 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -0,0 +1,196 @@ +// +// StoreAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class StoreAPI { + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Returns pet inventories by status + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - returns: RequestBuilder<[String: Int]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> URLSessionTask? { + return placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Place an order for a pet + - POST /store/order + - parameter body: (body) order placed for purchasing the pet + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift new file mode 100644 index 00000000000..3fc59f9ef4f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -0,0 +1,377 @@ +// +// UserAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class UserAPI { + + /** + Create user + + - parameter body: (body) Created user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + - parameter body: (body) Created user object + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let localVariablePath = "/user" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) The name that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Get user by user name + - GET /user/{username} + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> URLSessionTask? { + return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs user into the system + - GET /user/login + - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "username": username.encodeToJSON(), + "password": password.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Logs out current logged in user session + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift new file mode 100644 index 00000000000..09c82e53e13 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift new file mode 100644 index 00000000000..8fb05331889 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") + public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift new file mode 100644 index 00000000000..e2b73073804 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -0,0 +1,158 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return (200 ..< 300).contains(statusCode) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift new file mode 100644 index 00000000000..b79e9f5e64d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift @@ -0,0 +1,53 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift new file mode 100644 index 00000000000..02f78ffb470 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift new file mode 100644 index 00000000000..7787127c40d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -0,0 +1,80 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: HTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + header[key] = value + } + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift new file mode 100644 index 00000000000..621afb93561 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,36 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesClass: Codable, Hashable { + + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? + + public init(mapString: [String: String]? = nil, mapMapString: [String: [String: String]]? = nil) { + self.mapString = mapString + self.mapMapString = mapMapString + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapString = "map_string" + case mapMapString = "map_map_string" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift new file mode 100644 index 00000000000..cdd4f5335b9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -0,0 +1,36 @@ +// +// Animal.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Animal: Codable, Hashable { + + public var className: String + public var color: String? = "red" + + public init(className: String, color: String? = "red") { + self.className = className + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift new file mode 100644 index 00000000000..a0b09cb9761 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -0,0 +1,13 @@ +// +// AnimalFarm.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift new file mode 100644 index 00000000000..c365505ab9d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -0,0 +1,40 @@ +// +// ApiResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ApiResponse: Codable, Hashable { + + public var code: Int? + public var type: String? + public var message: String? + + public init(code: Int? = nil, type: String? = nil, message: String? = nil) { + self.code = code + self.type = type + self.message = message + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 00000000000..226f7456181 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { + + public var arrayArrayNumber: [[Double]]? + + public init(arrayArrayNumber: [[Double]]? = nil) { + self.arrayArrayNumber = arrayArrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayArrayNumber = "ArrayArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift new file mode 100644 index 00000000000..39831127871 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfNumberOnly: Codable, Hashable { + + public var arrayNumber: [Double]? + + public init(arrayNumber: [Double]? = nil) { + self.arrayNumber = arrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayNumber = "ArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift new file mode 100644 index 00000000000..8865d76bef2 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -0,0 +1,40 @@ +// +// ArrayTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayTest: Codable, Hashable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayOfString = "array_of_string" + case arrayArrayOfInteger = "array_array_of_integer" + case arrayArrayOfModel = "array_array_of_model" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift new file mode 100644 index 00000000000..71cd93bce5f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -0,0 +1,53 @@ +// +// Capitalization.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Capitalization: Codable, Hashable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case smallCamel + case capitalCamel = "CapitalCamel" + case smallSnake = "small_Snake" + case capitalSnake = "Capital_Snake" + case sCAETHFlowPoints = "SCA_ETH_Flow_Points" + case ATT_NAME + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift new file mode 100644 index 00000000000..457e04bd475 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -0,0 +1,40 @@ +// +// Cat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Cat: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var declawed: Bool? + + public init(className: String, color: String? = "red", declawed: Bool? = nil) { + self.className = className + self.color = color + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift new file mode 100644 index 00000000000..8caebb1c206 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -0,0 +1,32 @@ +// +// CatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CatAllOf: Codable, Hashable { + + public var declawed: Bool? + + public init(declawed: Bool? = nil) { + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift new file mode 100644 index 00000000000..89016ca353d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -0,0 +1,36 @@ +// +// Category.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Category: Codable, Hashable { + + public var id: Int64? + public var name: String? = "default-name" + + public init(id: Int64? = nil, name: String? = "default-name") { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift new file mode 100644 index 00000000000..16e69e560bd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -0,0 +1,33 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model with \"_class\" property */ +public struct ClassModel: Codable, Hashable { + + public var _class: String? + + public init(_class: String? = nil) { + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift new file mode 100644 index 00000000000..60dbc5dc5c1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -0,0 +1,32 @@ +// +// Client.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Client: Codable, Hashable { + + public var client: String? + + public init(client: String? = nil) { + self.client = client + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift new file mode 100644 index 00000000000..658732a7f36 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -0,0 +1,40 @@ +// +// Dog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Dog: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var breed: String? + + public init(className: String, color: String? = "red", breed: String? = nil) { + self.className = className + self.color = color + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift new file mode 100644 index 00000000000..82b0dedf35b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -0,0 +1,32 @@ +// +// DogAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DogAllOf: Codable, Hashable { + + public var breed: String? + + public init(breed: String? = nil) { + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift new file mode 100644 index 00000000000..321066b9f4e --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -0,0 +1,54 @@ +// +// EnumArrays.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumArrays: Codable, Hashable { + + public enum JustSymbol: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum ArrayEnum: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case fish = "fish" + case crab = "crab" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init(justSymbol: JustSymbol? = nil, arrayEnum: [ArrayEnum]? = nil) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justSymbol = "just_symbol" + case arrayEnum = "array_enum" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift new file mode 100644 index 00000000000..eef3045b291 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -0,0 +1,22 @@ +// +// EnumClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum EnumClass: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift new file mode 100644 index 00000000000..d6a96c72d97 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -0,0 +1,96 @@ +// +// EnumTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumTest: Codable, Hashable { + + public enum EnumString: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + case empty = "" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum EnumStringRequired: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + case empty = "" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum EnumInteger: Int, Codable, CaseIterable, CaseIterableDefaultsLast { + case _1 = 1 + case number1 = -1 + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + } + public enum EnumNumber: Double, Codable, CaseIterable, CaseIterableDefaultsLast { + case _11 = 1.1 + case number12 = -1.2 + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + } + public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init(enumString: EnumString? = nil, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger? = nil, enumNumber: EnumNumber? = nil, outerEnum: OuterEnum? = nil) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case enumString = "enum_string" + case enumStringRequired = "enum_string_required" + case enumInteger = "enum_integer" + case enumNumber = "enum_number" + case outerEnum + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift new file mode 100644 index 00000000000..05dd5b1a825 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -0,0 +1,34 @@ +// +// File.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Must be named `File` for test. */ +public struct File: Codable, Hashable { + + /** Test capitalization */ + public var sourceURI: String? + + public init(sourceURI: String? = nil) { + self.sourceURI = sourceURI + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift new file mode 100644 index 00000000000..3ca66a31359 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -0,0 +1,36 @@ +// +// FileSchemaTestClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FileSchemaTestClass: Codable, Hashable { + + public var file: File? + public var files: [File]? + + public init(file: File? = nil, files: [File]? = nil) { + self.file = file + self.files = files + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift new file mode 100644 index 00000000000..a7a4b39e720 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -0,0 +1,80 @@ +// +// FormatTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FormatTest: Codable, Hashable { + + public var integer: Int? + public var int32: Int? + public var int64: Int64? + public var number: Double + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data + public var binary: URL? + public var date: Date + public var dateTime: Date? + public var uuid: UUID? + public var password: String + + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift new file mode 100644 index 00000000000..54ed8a723c6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -0,0 +1,36 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HasOnlyReadOnly: Codable, Hashable { + + public var bar: String? + public var foo: String? + + public init(bar: String? = nil, foo: String? = nil) { + self.bar = bar + self.foo = foo + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift new file mode 100644 index 00000000000..67e3048469f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -0,0 +1,32 @@ +// +// List.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct List: Codable, Hashable { + + public var _123list: String? + + public init(_123list: String? = nil) { + self._123list = _123list + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _123list = "123-list" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift new file mode 100644 index 00000000000..c0b5a369451 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -0,0 +1,53 @@ +// +// MapTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MapTest: Codable, Hashable { + + public enum MapOfEnumString: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? + public var indirectMap: StringBooleanMap? + + public init(mapMapOfString: [String: [String: String]]? = nil, mapOfEnumString: [String: String]? = nil, directMap: [String: Bool]? = nil, indirectMap: StringBooleanMap? = nil) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + self.directMap = directMap + self.indirectMap = indirectMap + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapMapOfString = "map_map_of_string" + case mapOfEnumString = "map_of_enum_string" + case directMap = "direct_map" + case indirectMap = "indirect_map" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 00000000000..c79ca459217 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,40 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String: Animal]? + + public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift new file mode 100644 index 00000000000..23402143f71 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -0,0 +1,37 @@ +// +// Model200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name starting with number */ +public struct Model200Response: Codable, Hashable { + + public var name: Int? + public var _class: String? + + public init(name: Int? = nil, _class: String? = nil) { + self.name = name + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case _class = "class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift new file mode 100644 index 00000000000..a28f46a33ce --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -0,0 +1,45 @@ +// +// Name.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name same as property name */ +public struct Name: Codable, Hashable { + + public var name: Int + public var snakeCase: Int? + public var property: String? + public var _123number: Int? + + public init(name: Int, snakeCase: Int? = nil, property: String? = nil, _123number: Int? = nil) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123number = _123number + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case snakeCase = "snake_case" + case property + case _123number = "123Number" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift new file mode 100644 index 00000000000..87ceb64bb97 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -0,0 +1,32 @@ +// +// NumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NumberOnly: Codable, Hashable { + + public var justNumber: Double? + + public init(justNumber: Double? = nil) { + self.justNumber = justNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justNumber = "JustNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift new file mode 100644 index 00000000000..5615d10ff4c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -0,0 +1,63 @@ +// +// Order.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Order: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? = false + + public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) { + self.id = id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift new file mode 100644 index 00000000000..edeaccaeaa6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -0,0 +1,40 @@ +// +// OuterComposite.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OuterComposite: Codable, Hashable { + + public var myNumber: Double? + public var myString: String? + public var myBoolean: Bool? + + public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case myNumber = "my_number" + case myString = "my_string" + case myBoolean = "my_boolean" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift new file mode 100644 index 00000000000..e418b2c445b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -0,0 +1,22 @@ +// +// OuterEnum.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum OuterEnum: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift new file mode 100644 index 00000000000..81afbc4b2a1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -0,0 +1,63 @@ +// +// Pet.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Pet: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case available = "available" + case pending = "pending" + case sold = "sold" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var id: Int64? + public var category: Category? + public var name: String + public var photoUrls: [String] + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + self.id = id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift new file mode 100644 index 00000000000..57ba3f577c8 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -0,0 +1,36 @@ +// +// ReadOnlyFirst.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ReadOnlyFirst: Codable, Hashable { + + public var bar: String? + public var baz: String? + + public init(bar: String? = nil, baz: String? = nil) { + self.bar = bar + self.baz = baz + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift new file mode 100644 index 00000000000..afc2b51f8f3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -0,0 +1,33 @@ +// +// Return.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing reserved words */ +public struct Return: Codable, Hashable { + + public var _return: Int? + + public init(_return: Int? = nil) { + self._return = _return + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _return = "return" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift new file mode 100644 index 00000000000..bfe9723f888 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -0,0 +1,32 @@ +// +// SpecialModelName.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SpecialModelName: Codable, Hashable { + + public var specialPropertyName: Int64? + + public init(specialPropertyName: Int64? = nil) { + self.specialPropertyName = specialPropertyName + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case specialPropertyName = "$special[property.name]" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift new file mode 100644 index 00000000000..126c35c85a6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -0,0 +1,52 @@ +// +// StringBooleanMap.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StringBooleanMap: Codable, Hashable { + + + public enum CodingKeys: CodingKey, CaseIterable { + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + var nonAdditionalPropertyKeys = Set() + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift new file mode 100644 index 00000000000..07b826264f3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -0,0 +1,36 @@ +// +// Tag.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Tag: Codable, Hashable { + + public var id: Int64? + public var name: String? + + public init(id: Int64? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift new file mode 100644 index 00000000000..e58eecd960f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -0,0 +1,48 @@ +// +// TypeHolderDefault.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderDefault: Codable, Hashable { + + public var stringItem: String = "what" + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool = true + public var arrayItem: [Int] + + public init(stringItem: String = "what", numberItem: Double, integerItem: Int, boolItem: Bool = true, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift new file mode 100644 index 00000000000..6c22fdbae7a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -0,0 +1,48 @@ +// +// TypeHolderExample.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderExample: Codable, Hashable { + + public var stringItem: String + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool + public var arrayItem: [Int] + + public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift new file mode 100644 index 00000000000..7afe359ae40 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -0,0 +1,61 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct User: Codable, Hashable { + + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int? + + public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift new file mode 100644 index 00000000000..e06208074cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -0,0 +1,44 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } + return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift new file mode 100644 index 00000000000..acf7ff4031b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift @@ -0,0 +1,36 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + internal subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift new file mode 100644 index 00000000000..fe7fb6683bc --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -0,0 +1,609 @@ +// URLSessionImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if !os(macOS) +import MobileCoreServices +#endif + +class URLSessionRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return URLSessionRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return URLSessionDecodableRequestBuilder.self + } +} + +public typealias PetstoreClientAPIChallengeHandler = ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?)) + +// Store the URLSession's delegate to retain its reference +private let sessionDelegate = SessionDelegate() + +// Store the URLSession to retain its reference +private let defaultURLSession = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil) + +// Store current taskDidReceiveChallenge for every URLSessionTask +private var challengeHandlerStore = SynchronizedDictionary() + +// Store current URLCredential for every URLSessionTask +private var credentialStore = SynchronizedDictionary() + +open class URLSessionRequestBuilder: RequestBuilder { + + /** + May be assigned if you want to control the authentication challenges. + */ + public var taskDidReceiveChallenge: PetstoreClientAPIChallengeHandler? + + /** + May be assigned if you want to do any of those things: + - control the task completion + - intercept and handle errors like authorization + - retry the request. + */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") + public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the URLSession + configuration. + */ + open func createURLSession() -> URLSession { + return defaultURLSession + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the URLRequest + configuration (e.g. to override the cache policy). + */ + open func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + + guard let url = URL(string: URLString) else { + throw DownloadException.requestMissingURL + } + + var originalRequest = URLRequest(url: url) + + originalRequest.httpMethod = method.rawValue + + headers.forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + buildHeaders().forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) + + return modifiedRequest + } + + @discardableResult + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> URLSessionTask? { + let urlSession = createURLSession() + + guard let xMethod = HTTPMethod(rawValue: method) else { + fatalError("Unsupported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsupported Media Type - \(contentType)") + } + } + + do { + let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) + + var taskIdentifier: Int? + let cleanupRequest = { + if let taskIdentifier = taskIdentifier { + challengeHandlerStore[taskIdentifier] = nil + credentialStore[taskIdentifier] = nil + } + } + + let dataTask = urlSession.dataTask(with: request) { data, response, error in + + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { + + taskCompletionShouldRetry(data, response, error) { shouldRetry in + + if shouldRetry { + cleanupRequest() + self.execute(apiResponseQueue, completion) + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { + onProgressReady?(dataTask.progress) + } + + taskIdentifier = dataTask.taskIdentifier + challengeHandlerStore[dataTask.taskIdentifier] = taskDidReceiveChallenge + credentialStore[dataTask.taskIdentifier] = credential + + dataTask.resume() + + return dataTask + } catch { + apiResponseQueue.async { + completion(.failure(ErrorResponse.error(415, nil, nil, error))) + } + + return nil + } + } + + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: () as! T))) + + default: + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") + } + + } + + open func buildHeaders() -> [String: String] { + var httpHeaders: [String: String] = [:] + for (key, value) in headers { + httpHeaders[key] = value + } + for (key, value) in PetstoreClientAPI.customHeaders { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + continue + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { + override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as! T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as! T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: () as! T))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as! T))) + + default: + + guard let data = data, !data.isEmpty else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) + } + } + } +} + +private class SessionDelegate: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + + var credential: URLCredential? + + if let taskDidReceiveChallenge = challengeHandlerStore[task.taskIdentifier] { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = credentialStore[task.taskIdentifier] ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } +} + +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +public protocol ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest +} + +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters else { return urlRequest } + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) + urlRequest.url = urlComponents.url + } + + return urlRequest + } +} + +private class FormDataEncoding: ParameterEncoding { + + let contentTypeForFormPart: (_ fileURL: URL) -> String? + + init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) { + self.contentTypeForFormPart = contentTypeForFormPart + } + + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters, !parameters.isEmpty else { + return urlRequest + } + + let boundary = "Boundary-\(UUID().uuidString)" + + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + for (key, value) in parameters { + switch value { + case let fileURL as URL: + + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) + + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") + } + } + + var body = urlRequest.httpBody.orEmpty + + body.append("\r\n--\(boundary)--\r\n") + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + let fileData = try Data(contentsOf: fileURL) + + let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) + + let fileName = fileURL.lastPathComponent + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n") + body.append("Content-Type: \(mimetype)\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(fileData) + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(data) + + urlRequest.httpBody = body + + return urlRequest + + } + + func mimeType(for url: URL) -> String { + let pathExtension = url.pathExtension + + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + return "application/octet-stream" + } + +} + +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { + /// Append string to Data + /// + /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. + /// + /// - parameter string: The string to be added to the `Data`. + + mutating func append(_ string: String) { + if let data = string.data(using: .utf8) { + append(data) + } + } +} + +private extension Optional where Wrapped == Data { + var orEmpty: Data { + self ?? Data() + } +} + +extension JSONDataEncoding: ParameterEncoding {} diff --git a/samples/client/petstore/swift5/frozenEnums/README.md b/samples/client/petstore/swift5/frozenEnums/README.md new file mode 100644 index 00000000000..1725415f7e0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/README.md @@ -0,0 +1,141 @@ +# Swift5 API client for PetstoreClient + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeAPI* | [**fakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +*FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +*FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetAPI* | [**addPet**](docs/PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +*PetAPI* | [**deletePet**](docs/PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetAPI* | [**findPetsByStatus**](docs/PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetAPI* | [**findPetsByTags**](docs/PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetAPI* | [**getPetById**](docs/PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetAPI* | [**updatePet**](docs/PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +*PetAPI* | [**updatePetWithForm**](docs/PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetAPI* | [**uploadFile**](docs/PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetAPI* | [**uploadFileWithRequiredFile**](docs/PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreAPI* | [**getInventory**](docs/StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreAPI* | [**getOrderById**](docs/StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreAPI* | [**placeOrder**](docs/StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserAPI* | [**createUser**](docs/UserAPI.md#createuser) | **POST** /user | Create user +*UserAPI* | [**createUsersWithArrayInput**](docs/UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserAPI* | [**createUsersWithListInput**](docs/UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserAPI* | [**deleteUser**](docs/UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserAPI* | [**getUserByName**](docs/UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserAPI* | [**loginUser**](docs/UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +*UserAPI* | [**logoutUser**](docs/UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserAPI* | [**updateUser**](docs/UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Return](docs/Return.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..1f222244134 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: 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/swift5/frozenEnums/docs/Animal.md b/samples/client/petstore/swift5/frozenEnums/docs/Animal.md new file mode 100644 index 00000000000..69c601455cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to "red"] + +[[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/swift5/frozenEnums/docs/AnimalFarm.md b/samples/client/petstore/swift5/frozenEnums/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## 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/swift5/frozenEnums/docs/AnotherFakeAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/AnotherFakeAPI.md new file mode 100644 index 00000000000..26346e81a4c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AnotherFakeAPI.md @@ -0,0 +1,59 @@ +# AnotherFakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call123testSpecialTags** +```swift + open class func call123testSpecialTags(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test special tags +AnotherFakeAPI.call123testSpecialTags(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/ApiResponse.md b/samples/client/petstore/swift5/frozenEnums/docs/ApiResponse.md new file mode 100644 index 00000000000..c6d9768fe9b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/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/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..c6fceff5e08 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [[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/swift5/frozenEnums/docs/ArrayOfNumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..f09f8fa6f70 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[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/swift5/frozenEnums/docs/ArrayTest.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayTest.md new file mode 100644 index 00000000000..bf416b8330c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | [[Int64]] | | [optional] +**arrayArrayOfModel** | [[ReadOnlyFirst]] | | [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/swift5/frozenEnums/docs/Capitalization.md b/samples/client/petstore/swift5/frozenEnums/docs/Capitalization.md new file mode 100644 index 00000000000..95374216c77 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [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/swift5/frozenEnums/docs/Cat.md b/samples/client/petstore/swift5/frozenEnums/docs/Cat.md new file mode 100644 index 00000000000..fb5949b1576 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/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/swift5/frozenEnums/docs/CatAllOf.md b/samples/client/petstore/swift5/frozenEnums/docs/CatAllOf.md new file mode 100644 index 00000000000..79789be61c0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +## 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/swift5/frozenEnums/docs/Category.md b/samples/client/petstore/swift5/frozenEnums/docs/Category.md new file mode 100644 index 00000000000..5ca5408c0f9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [default to "default-name"] + +[[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/swift5/frozenEnums/docs/ClassModel.md b/samples/client/petstore/swift5/frozenEnums/docs/ClassModel.md new file mode 100644 index 00000000000..e3912fdf0fd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **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/swift5/frozenEnums/docs/Client.md b/samples/client/petstore/swift5/frozenEnums/docs/Client.md new file mode 100644 index 00000000000..0de1b238c36 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **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/swift5/frozenEnums/docs/Dog.md b/samples/client/petstore/swift5/frozenEnums/docs/Dog.md new file mode 100644 index 00000000000..4824786da04 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/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/swift5/frozenEnums/docs/DogAllOf.md b/samples/client/petstore/swift5/frozenEnums/docs/DogAllOf.md new file mode 100644 index 00000000000..9302ef52e93 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +## 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/swift5/frozenEnums/docs/EnumArrays.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumArrays.md new file mode 100644 index 00000000000..b9a9807d3c8 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[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/swift5/frozenEnums/docs/EnumClass.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/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/swift5/frozenEnums/docs/EnumTest.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumTest.md new file mode 100644 index 00000000000..bc9b036dd76 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Int** | | [optional] +**enumNumber** | **Double** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [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/swift5/frozenEnums/docs/FakeAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/FakeAPI.md new file mode 100644 index 00000000000..e33bd2d35fb --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FakeAPI.md @@ -0,0 +1,662 @@ +# FakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **fakeOuterBooleanSerialize** +```swift + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping (_ data: Bool?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer boolean types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = true // Bool | Input boolean as post body (optional) + +FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Bool** | Input boolean as post body | [optional] + +### Return type + +**Bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterCompositeSerialize** +```swift + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping (_ data: OuterComposite?, _ error: Error?) -> Void) +``` + + + +Test serialization of object with outer number type + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = OuterComposite(myNumber: 123, myString: "myString_example", myBoolean: false) // OuterComposite | Input composite as post body (optional) + +FakeAPI.fakeOuterCompositeSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterNumberSerialize** +```swift + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping (_ data: Double?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer number types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = 987 // Double | Input number as post body (optional) + +FakeAPI.fakeOuterNumberSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Double** | Input number as post body | [optional] + +### Return type + +**Double** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterStringSerialize** +```swift + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer string types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = "body_example" // String | Input string as post body (optional) + +FakeAPI.fakeOuterStringSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String** | Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **testBodyWithFileSchema** +```swift + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = FileSchemaTestClass(file: File(sourceURI: "sourceURI_example"), files: [nil]) // FileSchemaTestClass | + +FakeAPI.testBodyWithFileSchema(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testBodyWithQueryParams** +```swift + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let query = "query_example" // String | +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | + +FakeAPI.testBodyWithQueryParams(query: query, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String** | | + **body** | [**User**](User.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testClientModel** +```swift + open class func testClientModel(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test \"client\" model + +To test \"client\" model + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test \"client\" model +FakeAPI.testClientModel(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **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) + +# **testEndpointParameters** +```swift + open class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let integer = 987 // Int | None (optional) +let int32 = 987 // Int | None (optional) +let int64 = 987 // Int64 | None (optional) +let number = 987 // Double | None +let float = 987 // Float | None (optional) +let double = 987 // Double | None +let string = "string_example" // String | None (optional) +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = Data([9, 8, 7]) // Data | None +let binary = URL(string: "https://example.com")! // URL | None (optional) +let date = Date() // Date | None (optional) +let dateTime = Date() // Date | None (optional) +let password = "password_example" // String | None (optional) +let callback = "callback_example" // String | None (optional) + +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +FakeAPI.testEndpointParameters(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **integer** | **Int** | None | [optional] + **int32** | **Int** | None | [optional] + **int64** | **Int64** | None | [optional] + **number** | **Double** | None | + **float** | **Float** | None | [optional] + **double** | **Double** | None | + **string** | **String** | None | [optional] + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | + **binary** | **URL** | None | [optional] + **date** | **Date** | None | [optional] + **dateTime** | **Date** | None | [optional] + **password** | **String** | None | [optional] + **callback** | **String** | None | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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) + +# **testEnumParameters** +```swift + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +To test enum parameters + +To test enum parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional) +let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg) +let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional) +let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg) +let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional) +let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional) +let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar) +let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg) + +// To test enum parameters +FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg] + **enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional] + **enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg] + **enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar] + **enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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) + +# **testGroupParameters** +```swift + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let requiredStringGroup = 987 // Int | Required String in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters +let requiredInt64Group = 987 // Int64 | Required Integer in group parameters +let stringGroup = 987 // Int | String in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) +let int64Group = 987 // Int64 | Integer in group parameters (optional) + +// Fake endpoint to test group parameters (optional) +FakeAPI.testGroupParameters(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Int** | Required String in group parameters | + **requiredBooleanGroup** | **Bool** | Required Boolean in group parameters | + **requiredInt64Group** | **Int64** | Required Integer in group parameters | + **stringGroup** | **Int** | String in group parameters | [optional] + **booleanGroup** | **Bool** | Boolean in group parameters | [optional] + **int64Group** | **Int64** | Integer in group parameters | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **testInlineAdditionalProperties** +```swift + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test inline additionalProperties + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "TODO" // [String: String] | request body + +// test inline additionalProperties +FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | [**[String: String]**](String.md) | request body | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testJsonFormData** +```swift + open class func testJsonFormData(param: String, param2: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test json serialization of form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "param_example" // String | field1 +let param2 = "param2_example" // String | field2 + +// test json serialization of form data +FakeAPI.testJsonFormData(param: param, param2: param2) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String** | field1 | + **param2** | **String** | field2 | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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/swift5/frozenEnums/docs/FakeClassnameTags123API.md b/samples/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md new file mode 100644 index 00000000000..5b9b66073fe --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md @@ -0,0 +1,59 @@ +# FakeClassnameTags123API + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **testClassname** +```swift + open class func testClassname(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test class name in snake case + +To test class name in snake case + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test class name in snake case +FakeClassnameTags123API.testClassname(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/File.md b/samples/client/petstore/swift5/frozenEnums/docs/File.md new file mode 100644 index 00000000000..3edfef17b79 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [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/swift5/frozenEnums/docs/FileSchemaTestClass.md b/samples/client/petstore/swift5/frozenEnums/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..afdacc60b2c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [File] | | [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/swift5/frozenEnums/docs/FormatTest.md b/samples/client/petstore/swift5/frozenEnums/docs/FormatTest.md new file mode 100644 index 00000000000..f74d94f6c46 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Int** | | [optional] +**int32** | **Int** | | [optional] +**int64** | **Int64** | | [optional] +**number** | **Double** | | +**float** | **Float** | | [optional] +**double** | **Double** | | [optional] +**string** | **String** | | [optional] +**byte** | **Data** | | +**binary** | **URL** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **UUID** | | [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/swift5/frozenEnums/docs/HasOnlyReadOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..57b6e3a17e6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + +[[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/swift5/frozenEnums/docs/List.md b/samples/client/petstore/swift5/frozenEnums/docs/List.md new file mode 100644 index 00000000000..b77718302ed --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **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/swift5/frozenEnums/docs/MapTest.md b/samples/client/petstore/swift5/frozenEnums/docs/MapTest.md new file mode 100644 index 00000000000..73f9e0d50ac --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.md) | | [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/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..3fdfd03f0e3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [String: Animal] | | [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/swift5/frozenEnums/docs/Model200Response.md b/samples/client/petstore/swift5/frozenEnums/docs/Model200Response.md new file mode 100644 index 00000000000..5865ea690cc --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | [optional] +**_class** | **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/swift5/frozenEnums/docs/Name.md b/samples/client/petstore/swift5/frozenEnums/docs/Name.md new file mode 100644 index 00000000000..f7b180292cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | +**snakeCase** | **Int** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Int** | | [optional] [readonly] + +[[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/swift5/frozenEnums/docs/NumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/NumberOnly.md new file mode 100644 index 00000000000..72bd361168b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **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/swift5/frozenEnums/docs/Order.md b/samples/client/petstore/swift5/frozenEnums/docs/Order.md new file mode 100644 index 00000000000..15487f01175 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**petId** | **Int64** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **Date** | | [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/swift5/frozenEnums/docs/OuterComposite.md b/samples/client/petstore/swift5/frozenEnums/docs/OuterComposite.md new file mode 100644 index 00000000000..d6b3583bc3f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Double** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **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/swift5/frozenEnums/docs/OuterEnum.md b/samples/client/petstore/swift5/frozenEnums/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## 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/swift5/frozenEnums/docs/Pet.md b/samples/client/petstore/swift5/frozenEnums/docs/Pet.md new file mode 100644 index 00000000000..5c05f98fad4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [Tag] | | [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/swift5/frozenEnums/docs/PetAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md new file mode 100644 index 00000000000..37226f18b85 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md @@ -0,0 +1,469 @@ +# PetAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **addPet** +```swift + open class func addPet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Add a new pet to the store + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Add a new pet to the store +PetAPI.addPet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[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** +```swift + open class func deletePet(apiKey: String? = nil, petId: Int64, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Deletes a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let apiKey = "apiKey_example" // String | (optional) +let petId = 987 // Int64 | Pet id to delete + +// Deletes a pet +PetAPI.deletePet(apiKey: apiKey, petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **apiKey** | **String** | | [optional] + **petId** | **Int64** | Pet id to delete | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let status = ["status_example"] // [String] | Status values that need to be considered for filter + +// Finds Pets by status +PetAPI.findPetsByStatus(status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md) | Status values that need to be considered for filter | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByTags** +```swift + open class func findPetsByTags(tags: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let tags = ["inner_example"] // [String] | Tags to filter by + +// Finds Pets by tags +PetAPI.findPetsByTags(tags: tags) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md) | Tags to filter by | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getPetById** +```swift + open class func getPetById(petId: Int64, completion: @escaping (_ data: Pet?, _ error: Error?) -> Void) +``` + +Find pet by ID + +Returns a single pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to return + +// Find pet by ID +PetAPI.getPetById(petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePet** +```swift + open class func updatePet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Update an existing pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Update an existing pet +PetAPI.updatePet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[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** +```swift + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updates a pet in the store with form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet that needs to be updated +let name = "name_example" // String | Updated name of the pet (optional) +let status = "status_example" // String | Updated status of the pet (optional) + +// Updates a pet in the store with form data +PetAPI.updatePetWithForm(petId: petId, name: name, status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet that needs to be updated | + **name** | **String** | Updated name of the pet | [optional] + **status** | **String** | Updated status of the pet | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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** +```swift + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let file = URL(string: "https://example.com")! // URL | file to upload (optional) + +// uploads an image +PetAPI.uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **file** | **URL** | file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **uploadFileWithRequiredFile** +```swift + open class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image (required) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let requiredFile = URL(string: "https://example.com")! // URL | file to upload + +// uploads an image (required) +PetAPI.uploadFileWithRequiredFile(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **requiredFile** | **URL** | file to upload | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md b/samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..ed537b87598 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **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/swift5/frozenEnums/docs/Return.md b/samples/client/petstore/swift5/frozenEnums/docs/Return.md new file mode 100644 index 00000000000..66d17c27c88 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## 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/swift5/frozenEnums/docs/SpecialModelName.md b/samples/client/petstore/swift5/frozenEnums/docs/SpecialModelName.md new file mode 100644 index 00000000000..3ec27a38c2a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Int64** | | [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/swift5/frozenEnums/docs/StoreAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/StoreAPI.md new file mode 100644 index 00000000000..b023aa9e452 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/StoreAPI.md @@ -0,0 +1,206 @@ +# StoreAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +```swift + open class func deleteOrder(orderId: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = "orderId_example" // String | ID of the order that needs to be deleted + +// Delete purchase order by ID +StoreAPI.deleteOrder(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String** | ID of the order that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Returns pet inventories by status +StoreAPI.getInventory() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**[String: Int]** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getOrderById** +```swift + open class func getOrderById(orderId: Int64, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = 987 // Int64 | ID of pet that needs to be fetched + +// Find purchase order by ID +StoreAPI.getOrderById(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Int64** | ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **placeOrder** +```swift + open class func placeOrder(body: Order, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Place an order for a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Order(id: 123, petId: 123, quantity: 123, shipDate: Date(), status: "status_example", complete: false) // Order | order placed for purchasing the pet + +// Place an order for a pet +StoreAPI.placeOrder(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md) | order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md b/samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md new file mode 100644 index 00000000000..7abf11ec68b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# StringBooleanMap + +## 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/swift5/frozenEnums/docs/Tag.md b/samples/client/petstore/swift5/frozenEnums/docs/Tag.md new file mode 100644 index 00000000000..ff4ac8aa451 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [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/swift5/frozenEnums/docs/TypeHolderDefault.md b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderDefault.md new file mode 100644 index 00000000000..5161394bdc3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderDefault.md @@ -0,0 +1,14 @@ +# TypeHolderDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | [default to "what"] +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | [default to true] +**arrayItem** | **[Int]** | | + +[[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/swift5/frozenEnums/docs/TypeHolderExample.md b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderExample.md new file mode 100644 index 00000000000..46d0471cd71 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderExample.md @@ -0,0 +1,14 @@ +# TypeHolderExample + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | +**arrayItem** | **[Int]** | | + +[[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/swift5/frozenEnums/docs/User.md b/samples/client/petstore/swift5/frozenEnums/docs/User.md new file mode 100644 index 00000000000..5a439de0ff9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **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/swift5/frozenEnums/docs/UserAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/UserAPI.md new file mode 100644 index 00000000000..5fc9160daf4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/UserAPI.md @@ -0,0 +1,406 @@ +# UserAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserAPI.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +# **createUser** +```swift + open class func createUser(body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Create user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Created user object + +// Create user +UserAPI.createUser(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md) | Created user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func createUsersWithArrayInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithArrayInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func createUsersWithListInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithListInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func deleteUser(username: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be deleted + +// Delete user +UserAPI.deleteUser(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func getUserByName(username: String, completion: @escaping (_ data: User?, _ error: Error?) -> Void) +``` + +Get user by user name + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be fetched. Use user1 for testing. + +// Get user by user name +UserAPI.getUserByName(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **loginUser** +```swift + open class func loginUser(username: String, password: String, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + +Logs user into the system + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The user name for login +let password = "password_example" // String | The password for login in clear text + +// Logs user into the system +UserAPI.loginUser(username: username, password: password) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The user name for login | + **password** | **String** | The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logoutUser** +```swift + open class func logoutUser(completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Logs out current logged in user session + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Logs out current logged in user session +UserAPI.logoutUser() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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** +```swift + open class func updateUser(username: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updated user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | name that need to be deleted +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Updated user object + +// Updated user +UserAPI.updateUser(username: username, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | name that need to be deleted | + **body** | [**User**](User.md) | Updated user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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/swift5/frozenEnums/git_push.sh b/samples/client/petstore/swift5/frozenEnums/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/git_push.sh @@ -0,0 +1,57 @@ +#!/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 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/swift5/frozenEnums/pom.xml b/samples/client/petstore/swift5/frozenEnums/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/frozenEnums/project.yml b/samples/client/petstore/swift5/frozenEnums/project.yml new file mode 100644 index 00000000000..0493cf65896 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 1.0.0 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh b/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index a5bf5a193ef..31c875915ac 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ internal class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + internal class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ internal class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0441d91c094..74aa56a14e6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ internal class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + internal class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ internal class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - internal class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + internal class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 0c1c7548898..60869f63ef6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + internal enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md index d18c9425010..1cc75c5aab2 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + internal class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md index eb2db2040cd..a9e13c339cf 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - internal class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + internal class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58208b46ee7..5396fe8dd32 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ import AnyCodable - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ import AnyCodable - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 6ee48721751..58fbeae4d63 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ import AnyCodable - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ import AnyCodable - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md index c0a0824fb70..a75c5864f1c 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md index b3187a51128..5e6bccd7eaa 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift index d58ad1f8b31..c249774d2a2 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift @@ -10,7 +10,7 @@ import Foundation import AnyCodable #endif -public enum Fruit: Codable { +public enum Fruit: Codable, Hashable { case typeApple(Apple) case typeBanana(Banana) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index ef784bfffdc..17beed78a8e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -493,7 +493,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEnumParameters( enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { @@ -520,7 +520,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a6de43f3870..11c84c86433 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -128,7 +128,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[Pet]> */ - open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByStatus( status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { @@ -151,7 +151,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md index 0d4d1a6ce26..5164a64867d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md @@ -416,7 +416,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise + open class func testEnumParameters( enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise ``` To test enum parameters diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md index 8a516ca3014..41d27fed4e7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md @@ -109,7 +109,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus( status: [String]) -> Promise<[Pet]> + open class func findPetsByStatus( status: [Status_findPetsByStatus]) -> Promise<[Pet]> ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 1bb864f1684..db0c4cb351c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index ff5d3c3db10..33bc3ed33a9 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 7836542dbe0..4d998a53217 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -533,7 +533,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in let task = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { @@ -565,7 +565,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1f346ba1019..73e4a43c655 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -138,7 +138,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[Pet]> */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in let task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { @@ -166,7 +166,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md index aecb7880a3c..350928e8e7f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md @@ -366,7 +366,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Observable + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Observable ``` To test enum parameters diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md index a87db33f46d..9f9a42ca4f5 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md @@ -95,7 +95,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String]) -> Observable<[Pet]> + open class func findPetsByStatus(status: [Status_findPetsByStatus]) -> Observable<[Pet]> ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/swift5_test_all.sh b/samples/client/petstore/swift5/swift5_test_all.sh index f621187c463..faeb4ca6aa1 100755 --- a/samples/client/petstore/swift5/swift5_test_all.sh +++ b/samples/client/petstore/swift5/swift5_test_all.sh @@ -19,6 +19,7 @@ mvn -f $DIRECTORY/alamofireLibrary/pom.xml integration-test mvn -f $DIRECTORY/combineLibrary/pom.xml integration-test mvn -f $DIRECTORY/default/pom.xml integration-test mvn -f $DIRECTORY/deprecated/pom.xml integration-test +mvn -f $DIRECTORY/frozenEnums/pom.xml integration-test mvn -f $DIRECTORY/nonPublicApi/pom.xml integration-test mvn -f $DIRECTORY/objcCompatible/pom.xml integration-test mvn -f $DIRECTORY/oneOf/pom.xml integration-test diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift index 016a94b531a..80d050c6d3e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -488,7 +488,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -513,7 +513,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift index 2bbb5aba079..ffcf8725e94 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -129,7 +129,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -150,7 +150,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md index cc68117f304..2cb0e52af6d 100644 --- a/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md @@ -575,7 +575,7 @@ public enum TestEndpointParameters { # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture ``` To test enum parameters diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md index f93e01e6d5d..3fc719012eb 100644 --- a/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md @@ -137,7 +137,7 @@ public enum DeletePet { # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture + open class func findPetsByStatus(status: [Status_findPetsByStatus], headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES new file mode 100644 index 00000000000..7f8ebffb302 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md new file mode 100644 index 00000000000..f2e5a1c1ee2 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md @@ -0,0 +1,203 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts new file mode 100644 index 00000000000..2afb8f64e92 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts new file mode 100644 index 00000000000..8e44b64083d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts new file mode 100644 index 00000000000..4e6194e7b10 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts @@ -0,0 +1,666 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts new file mode 100644 index 00000000000..9d00e8b652c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts @@ -0,0 +1,311 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * @param body order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts new file mode 100644 index 00000000000..7fc46dada8a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts @@ -0,0 +1,549 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts new file mode 100644 index 00000000000..6fc0f80d973 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts @@ -0,0 +1,141 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh @@ -0,0 +1,57 @@ +#!/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 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts new file mode 100644 index 00000000000..682ba478921 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts new file mode 100644 index 00000000000..b988b6827a0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts new file mode 100644 index 00000000000..8607c5dabd0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts new file mode 100644 index 00000000000..a29bebe4906 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts @@ -0,0 +1,37 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts new file mode 100644 index 00000000000..e0404395f91 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts @@ -0,0 +1,39 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +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 const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts new file mode 100644 index 00000000000..b6ff210e8df --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts new file mode 100644 index 00000000000..fce51005300 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts @@ -0,0 +1,30 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES new file mode 100644 index 00000000000..5db7bd76369 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +ng-package.json +package.json +tsconfig.json +variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md new file mode 100644 index 00000000000..000c51d694b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md @@ -0,0 +1,203 @@ +## @openapitools/typescript-angular-petstore@1.0.0 + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @openapitools/typescript-angular-petstore@1.0.0 --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link @openapitools/typescript-angular-petstore +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from '@openapitools/typescript-angular-petstore'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@openapitools/typescript-angular-petstore'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@openapitools/typescript-angular-petstore'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts new file mode 100644 index 00000000000..2afb8f64e92 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts new file mode 100644 index 00000000000..8e44b64083d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts new file mode 100644 index 00000000000..4e6194e7b10 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts @@ -0,0 +1,666 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts new file mode 100644 index 00000000000..9d00e8b652c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts @@ -0,0 +1,311 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * @param body order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts new file mode 100644 index 00000000000..7fc46dada8a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts @@ -0,0 +1,549 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts new file mode 100644 index 00000000000..6fc0f80d973 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts @@ -0,0 +1,141 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh @@ -0,0 +1,57 @@ +#!/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 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts new file mode 100644 index 00000000000..682ba478921 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts new file mode 100644 index 00000000000..b988b6827a0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts new file mode 100644 index 00000000000..8607c5dabd0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts new file mode 100644 index 00000000000..a29bebe4906 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts @@ -0,0 +1,37 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts new file mode 100644 index 00000000000..e0404395f91 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts @@ -0,0 +1,39 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +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 const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts new file mode 100644 index 00000000000..b6ff210e8df --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts new file mode 100644 index 00000000000..fce51005300 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts @@ -0,0 +1,30 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json new file mode 100644 index 00000000000..3b17900dc9c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json new file mode 100644 index 00000000000..a00df3cd562 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json @@ -0,0 +1,34 @@ +{ + "name": "@openapitools/typescript-angular-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-angular-petstore", + "author": "OpenAPI-Generator Contributors", + "keywords": [ + "openapi-client", + "openapi-generator" + ], + "license": "Unlicense", + "scripts": { + "build": "ng-packagr -p ng-package.json" + }, + "peerDependencies": { + "@angular/core": "^13.0.1", + "rxjs": "^7.4.0" + }, + "devDependencies": { + "@angular/common": "^13.0.1", + "@angular/compiler": "^13.0.1", + "@angular/compiler-cli": "^13.0.1", + "@angular/core": "^13.0.1", + "@angular/platform-browser": "^13.0.1", + "ng-packagr": "^13.0.3", + "reflect-metadata": "^0.1.3", + "rxjs": "^7.4.0", + "tsickle": "^0.43.0", + "typescript": ">=4.4.2 <4.5.0", + "zone.js": "^0.11.4" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json new file mode 100644 index 00000000000..fd2abf8a2ad --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es6", + "module": "es6", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart index 1b807addf9e..5ee82d7b501 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart @@ -110,26 +110,22 @@ part 'serializers.g.dart'; User, ]) Serializers serializers = (_$serializers.toBuilder() - ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) ..addBuilderFactory( const FullType(BuiltMap, [FullType(String), FullType(String)]), () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) - ..addBuilderFactory( - const FullType(BuiltSet, [FullType(Pet)]), - () => SetBuilder(), + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), ) ..addBuilderFactory( const FullType(BuiltSet, [FullType(String)]), () => SetBuilder(), ) + ..addBuilderFactory( + const FullType(BuiltSet, [FullType(Pet)]), + () => SetBuilder(), + ) ..addBuilderFactory( const FullType(BuiltList, [FullType(Pet)]), () => ListBuilder(), @@ -139,8 +135,8 @@ Serializers serializers = (_$serializers.toBuilder() () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(User)]), - () => ListBuilder(), + const FullType(BuiltList, [FullType(String)]), + () => ListBuilder(), ) ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart index 1b807addf9e..5ee82d7b501 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart @@ -110,26 +110,22 @@ part 'serializers.g.dart'; User, ]) Serializers serializers = (_$serializers.toBuilder() - ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) ..addBuilderFactory( const FullType(BuiltMap, [FullType(String), FullType(String)]), () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) - ..addBuilderFactory( - const FullType(BuiltSet, [FullType(Pet)]), - () => SetBuilder(), + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), ) ..addBuilderFactory( const FullType(BuiltSet, [FullType(String)]), () => SetBuilder(), ) + ..addBuilderFactory( + const FullType(BuiltSet, [FullType(Pet)]), + () => SetBuilder(), + ) ..addBuilderFactory( const FullType(BuiltList, [FullType(Pet)]), () => ListBuilder(), @@ -139,8 +135,8 @@ Serializers serializers = (_$serializers.toBuilder() () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(User)]), - () => ListBuilder(), + const FullType(BuiltList, [FullType(String)]), + () => ListBuilder(), ) ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) diff --git a/samples/server/petstore/php-slim4/README.md b/samples/server/petstore/php-slim4/README.md index 5dc80231b17..ac51de45d1e 100644 --- a/samples/server/petstore/php-slim4/README.md +++ b/samples/server/petstore/php-slim4/README.md @@ -8,7 +8,7 @@ This server has been generated with [Slim PSR-7](https://github.com/slimphp/Slim ## Requirements * Web server with URL rewriting -* PHP 7.3 or newer +* PHP 7.4 or newer This package contains `.htaccess` for Apache configuration. If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc. diff --git a/samples/server/petstore/php-slim4/composer.json b/samples/server/petstore/php-slim4/composer.json index da7b26a6d4f..529f8f93715 100644 --- a/samples/server/petstore/php-slim4/composer.json +++ b/samples/server/petstore/php-slim4/composer.json @@ -8,7 +8,7 @@ } ], "require": { - "php": "^7.3 || ^8.0", + "php": "^7.4 || ^8.0", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", "ybelenko/openapi-data-mocker": "^1.0", diff --git a/samples/server/petstore/php-slim4/config/dev/example.inc.php b/samples/server/petstore/php-slim4/config/dev/example.inc.php index 9d461dca380..2a2e65d4a59 100644 --- a/samples/server/petstore/php-slim4/config/dev/example.inc.php +++ b/samples/server/petstore/php-slim4/config/dev/example.inc.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/config/prod/example.inc.php b/samples/server/petstore/php-slim4/config/prod/example.inc.php index 9d461dca380..2a2e65d4a59 100644 --- a/samples/server/petstore/php-slim4/config/prod/example.inc.php +++ b/samples/server/petstore/php-slim4/config/prod/example.inc.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php index 3565cbc42c6..ff8c7224526 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php index af982bec785..2542047a669 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php index ee99c33e8ae..eee2c7d2ccf 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php index 42ea8a34d49..de2e6011364 100644 --- a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php +++ b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/BaseModel.php b/samples/server/petstore/php-slim4/lib/BaseModel.php index a8330177973..b0040c1a557 100644 --- a/samples/server/petstore/php-slim4/lib/BaseModel.php +++ b/samples/server/petstore/php-slim4/lib/BaseModel.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php b/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php index 993224f6c87..b1199ffd84a 100644 --- a/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php +++ b/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php b/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php index 6368eb2c726..bd0edc18f10 100644 --- a/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php +++ b/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Category.php b/samples/server/petstore/php-slim4/lib/Model/Category.php index 8e1c6e1b653..584fe5d7d3b 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Category.php +++ b/samples/server/petstore/php-slim4/lib/Model/Category.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Order.php b/samples/server/petstore/php-slim4/lib/Model/Order.php index 52dfff78c0a..1422e6efcf4 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Order.php +++ b/samples/server/petstore/php-slim4/lib/Model/Order.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Pet.php b/samples/server/petstore/php-slim4/lib/Model/Pet.php index c400e3208de..f249c10dfac 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Pet.php +++ b/samples/server/petstore/php-slim4/lib/Model/Pet.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Tag.php b/samples/server/petstore/php-slim4/lib/Model/Tag.php index 4606b83ae88..81d7a6e26a6 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Tag.php +++ b/samples/server/petstore/php-slim4/lib/Model/Tag.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/User.php b/samples/server/petstore/php-slim4/lib/Model/User.php index 5fb9f025cd0..68494ec67b5 100644 --- a/samples/server/petstore/php-slim4/lib/Model/User.php +++ b/samples/server/petstore/php-slim4/lib/Model/User.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/SlimRouter.php b/samples/server/petstore/php-slim4/lib/SlimRouter.php index fcc1a818d6c..c0b9c2bda9f 100644 --- a/samples/server/petstore/php-slim4/lib/SlimRouter.php +++ b/samples/server/petstore/php-slim4/lib/SlimRouter.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/public/index.php b/samples/server/petstore/php-slim4/public/index.php index 17511cbfb7a..07ab220a086 100644 --- a/samples/server/petstore/php-slim4/public/index.php +++ b/samples/server/petstore/php-slim4/public/index.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/tests/BaseModelTest.php b/samples/server/petstore/php-slim4/tests/BaseModelTest.php index 49927e56871..33325cc198c 100644 --- a/samples/server/petstore/php-slim4/tests/BaseModelTest.php +++ b/samples/server/petstore/php-slim4/tests/BaseModelTest.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team