Compare commits

..

12 Commits

Author SHA1 Message Date
William Cheng
663ae41ad3 Merge branch 'patch-1' of https://github.com/aronkankel/openapi-generator into aronkankel-patch-1 2024-01-29 19:39:22 +08:00
Aron
ef94ee7a9f Merge pull request #1 from aronkankel/master
Fix for generated files
2024-01-26 16:50:45 +01:00
Aron
212dfb899b Merge branch 'OpenAPITools:master' into master 2024-01-26 16:44:17 +01:00
Aron
fe2ca3abb2 Merge branch 'OpenAPITools:master' into patch-1 2024-01-26 16:36:17 +01:00
Aron
9e1271fa83 FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:33:37 +01:00
Aron
159c86cafa FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:32:16 +01:00
Aron
0ab8c2c769 FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:30:50 +01:00
Aron
c6fbbfc2cb FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:29:16 +01:00
Aron
1bbd7c0f2f FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:27:30 +01:00
Aron
3aac4a8685 FakeApi.cs generated based on new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:25:58 +01:00
Aron
bb4b5034d3 MultipartApi.cs generated with new mustache
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-26 16:22:34 +01:00
Aron
592968e28e FormParameters correct handling for "isPrimitiveType"
https://github.com/OpenAPITools/openapi-generator/issues/17699
2024-01-24 17:51:19 +01:00
861 changed files with 1598 additions and 39821 deletions

View File

@@ -29,7 +29,7 @@ jobs:
- name: Run echo server
run: |
git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server
(cd http-echo-server && git checkout 15a684c41d4de692878636f47fcc1670af309a0f && npm install && npm start &)
(cd http-echo-server && npm install && npm start &)
- name: Install
working-directory: ${{ matrix.sample }}

26
.github/workflows/sonar.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Sonar CI
on:
push:
branches:
- master
- '[4-9]+.[0-9]+.x'
- sonar
jobs:
build:
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'OpenAPITools' }}
steps:
- uses: actions/checkout@v4
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 11
- name: Compile with Maven
run: ./mvnw -B -q clean install jacoco:report
- name: Jacoco Aggregate
run: ./mvnw jacoco:report-aggregate
- name: Publish to Sonar
run: ./mvnw -B -q -nsu sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/}

View File

@@ -66,8 +66,6 @@ If you find OpenAPI Generator useful for work, please consider asking your compa
[<img src="https://openapi-generator.tech/img/companies/fornex.png" width="128" height="128">](https://fornex.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/alloyautomation.png" width="128" height="128">](https://runalloy.com/signup?utm_source=github&utm_medium=referral&utm_campaign=1524_openapigenerator)
[<img src="https://openapi-generator.tech/img/companies/ssstwitter.png" width="128" height="128">](https://ssstwitter.com/?utm_source=github&utm_medium=referral&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/svix.png" width="128" height="128">](https://www.svix.com/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship)
#### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS, Checkly for sponsoring the API monitoring and Gradle for sponsoring Develocity
@@ -708,7 +706,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Splitit](https://www.splitit.com/)
- [Stingray](http://www.stingray.com)
- [Suva](https://www.suva.ch/)
- [Svix](https://www.svix.com/)
- [Telstra](https://dev.telstra.com)
- [Tencent](https://www.tencent.com)
- [The University of Aizu](https://www.u-aizu.ac.jp/en/)

View File

@@ -1,6 +0,0 @@
generatorName: go
outputDir: samples/client/echo_api/go-external-refs
inputSpec: modules/openapi-generator/src/test/resources/3_0/external-refs/echo_api.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -1,5 +0,0 @@
generatorName: go
outputDir: samples/client/others/go/oneof-anyof-required
inputSpec: modules/openapi-generator/src/test/resources/3_0/go/spec-with-oneof-anyof-required.yaml
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -17,6 +17,3 @@ additionalProperties:
enumNameMappings:
s: LOWER_CASE_S
S: UPPER_CASE_S
operationIdNameMappings:
getArrayOfEnums: getFakeArrayofenums
fakeHealthGet: getFakeHealth

View File

@@ -10,7 +10,7 @@
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ClientTest.java"
sha256: db505f7801fef62c13a08a8e9ca1fc4c5c947ab46b46f12943139d353feacf17
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java"
sha256: c479b587cf0d51fa550eb81d33b277081807b87dc28649027d1164224c25ad0a
sha256: 7b9514ac0b3730685590d6ef273b2c2a1fb72d968529c2423a139ee9b0b92a65
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java"
sha256: 0d64cdc11809a7b5b952ccdad2bd91bd0045b3894d6fabf3e368fa0be12b8217
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java"

View File

@@ -436,13 +436,6 @@ Not all generators support thess features yet. Please give it a try to confirm t
NOTE: some generators use `baseName` (original name obtained direclty from OpenAPI spec, e.g. `shipping-date`) mustache tag in the templates so the mapping feature won't work.
To map `operationId` (used in method naming) to something else, use `operationIdNameMappings` option, e.g.
```sh
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/java/ --operation-id-name-mappings getPetById=returnPetById
```
will name the API method as `returnPetById` instead of `getPetById` obtained from OpenAPI doc/spec.
## Schema Mapping
One can map the schema to something else (e.g. external objects/models outside of the package) using the `schemaMappings` option, e.g. in CLI
@@ -578,9 +571,3 @@ Example:
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml -o /tmp/java-okhttp/ --openapi-normalizer REFACTOR_ALLOF_WITH_PROPERTIES_ONLY=true
```
- `REMOVE_X_INTERNAL`: When set to true, remove `x-internal` extension from operations and models.
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer REMOVE_X_INTERNAL=true
```

View File

@@ -125,12 +125,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>reinterpret_cast</li>
<li>requires</li>
<li>return</li>
<li>set</li>
<li>short</li>
<li>signals</li>
<li>signed</li>
<li>sizeof</li>
<li>slots</li>
<li>static</li>
<li>static_assert</li>
<li>static_cast</li>
@@ -148,7 +145,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>union</li>
<li>unsigned</li>
<li>using</li>
<li>valid</li>
<li>virtual</li>
<li>void</li>
<li>volatile</li>

View File

@@ -123,10 +123,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>requires</li>
<li>return</li>
<li>short</li>
<li>signals</li>
<li>signed</li>
<li>sizeof</li>
<li>slots</li>
<li>static</li>
<li>static_assert</li>
<li>static_cast</li>

View File

@@ -32,7 +32,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|licenseName|The name of the license| |null|
|modelPackage|package for generated models| |null|
|modern|use modern language features (generated code will require PHP 8.1)| |false|
|modern|use modern language features (generated code will require PHP 8.0)| |false|
|packageName|The main package name for classes. e.g. GeneratedPetstore| |null|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -92,9 +92,6 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
@Option(name = {"--enum-name-mappings"}, title = "enum name mappings", description = "displays the enum name mappings (none)")
private Boolean enumNameMappings;
@Option(name = {"--operation-id-name-mappings"}, title = "operation id name mappings", description = "displays the operation id name mappings (none)")
private Boolean operationIdNameMappings;
@Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)")
private Boolean openapiNormalizer;
@@ -563,18 +560,6 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
sb.append(newline);
}
if (Boolean.TRUE.equals(operationIdNameMappings)) {
sb.append(newline).append("OPERATION ID MAPPING").append(newline).append(newline);
Map<String, String> map = config.operationIdNameMapping()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {
throw new IllegalStateException(String.format(Locale.ROOT, "Duplicated options! %s and %s", a, b));
}, TreeMap::new));
writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "operation id name", "Mapped to");
sb.append(newline);
}
if (Boolean.TRUE.equals(openapiNormalizer)) {
sb.append(newline).append("OPENAPI NORMALIZER RULES").append(newline).append(newline);
Map<String, String> map = config.openapiNormalizer()

View File

@@ -223,13 +223,6 @@ public class Generate extends OpenApiGeneratorCommand {
+ " You can also have multiple occurrences of this option.")
private List<String> enumNameMappings = new ArrayList<>();
@Option(
name = {"--operation-id-name-mappings"},
title = "operation id name mappings",
description = "specifies mappings between the operation id name and the new name in the format of operation_id_name=AnotherName,operation_id_name2=OtherName2."
+ " You can also have multiple occurrences of this option.")
private List<String> operationIdNameMappings = new ArrayList<>();
@Option(
name = {"--openapi-normalizer"},
title = "OpenAPI normalizer rules",
@@ -514,7 +507,6 @@ public class Generate extends OpenApiGeneratorCommand {
applyParameterNameMappingsKvpList(parameterNameMappings, configurator);
applyModelNameMappingsKvpList(modelNameMappings, configurator);
applyEnumNameMappingsKvpList(enumNameMappings, configurator);
applyOperationIdNameMappingsKvpList(operationIdNameMappings, configurator);
applyOpenAPINormalizerKvpList(openapiNormalizer, configurator);
applyTypeMappingsKvpList(typeMappings, configurator);
applyAdditionalPropertiesKvpList(additionalProperties, configurator);

View File

@@ -6,7 +6,7 @@
<artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -57,7 +57,6 @@ public final class GeneratorSettings implements Serializable {
private final Map<String, String> parameterNameMappings;
private final Map<String, String> modelNameMappings;
private final Map<String, String> enumNameMappings;
private final Map<String, String> operationIdNameMappings;
private final Map<String, String> openapiNormalizer;
private final Set<String> languageSpecificPrimitives;
private final Set<String> openapiGeneratorIgnoreList;
@@ -307,15 +306,6 @@ public final class GeneratorSettings implements Serializable {
return enumNameMappings;
}
/**
* Gets operation id name mappings between an operation id name and the new name.
*
* @return the operation id name mappings
*/
public Map<String, String> getOperationIdNameMappings() {
return operationIdNameMappings;
}
/**
* Gets OpenAPI normalizer rules
*
@@ -456,7 +446,6 @@ public final class GeneratorSettings implements Serializable {
parameterNameMappings = Collections.unmodifiableMap(builder.parameterNameMappings);
modelNameMappings = Collections.unmodifiableMap(builder.modelNameMappings);
enumNameMappings = Collections.unmodifiableMap(builder.enumNameMappings);
operationIdNameMappings = Collections.unmodifiableMap(builder.operationIdNameMappings);
openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer);
languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives);
openapiGeneratorIgnoreList = Collections.unmodifiableSet(builder.openapiGeneratorIgnoreList);
@@ -536,7 +525,6 @@ public final class GeneratorSettings implements Serializable {
parameterNameMappings = Collections.unmodifiableMap(new HashMap<>(0));
modelNameMappings = Collections.unmodifiableMap(new HashMap<>(0));
enumNameMappings = Collections.unmodifiableMap(new HashMap<>(0));
operationIdNameMappings = Collections.unmodifiableMap(new HashMap<>(0));
openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0));
languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0));
openapiGeneratorIgnoreList = Collections.unmodifiableSet(new HashSet<>(0));
@@ -611,9 +599,6 @@ public final class GeneratorSettings implements Serializable {
if (copy.getEnumNameMappings() != null) {
builder.enumNameMappings.putAll(copy.getEnumNameMappings());
}
if (copy.getOperationIdNameMappings() != null) {
builder.operationIdNameMappings.putAll(copy.getOperationIdNameMappings());
}
if (copy.getOpenAPINormalizer() != null) {
builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer());
}
@@ -666,7 +651,6 @@ public final class GeneratorSettings implements Serializable {
private Map<String, String> parameterNameMappings;
private Map<String, String> modelNameMappings;
private Map<String, String> enumNameMappings;
private Map<String, String> operationIdNameMappings;
private Map<String, String> openapiNormalizer;
private Set<String> languageSpecificPrimitives;
private Set<String> openapiGeneratorIgnoreList;
@@ -693,7 +677,6 @@ public final class GeneratorSettings implements Serializable {
parameterNameMappings = new HashMap<>();
modelNameMappings = new HashMap<>();
enumNameMappings = new HashMap<>();
operationIdNameMappings = new HashMap<>();
openapiNormalizer = new HashMap<>();
languageSpecificPrimitives = new HashSet<>();
openapiGeneratorIgnoreList = new HashSet<>();
@@ -1120,32 +1103,6 @@ public final class GeneratorSettings implements Serializable {
return this;
}
/**
* Sets the {@code operationIdNameMappings} and returns a reference to this Builder so that the methods can be chained together.
*
* @param operationIdNameMappings the {@code operationIdNameMappings} to set
* @return a reference to this Builder
*/
public Builder withOperationIdNameMappings(Map<String, String> operationIdNameMappings) {
this.operationIdNameMappings = operationIdNameMappings;
return this;
}
/**
* Sets a single {@code operationIdNameMappings} and returns a reference to this Builder so that the methods can be chained together.
*
* @param key A key for the name mapping
* @param value The value of name mapping
* @return a reference to this Builder
*/
public Builder withOperationIdNameMapping(String key, String value) {
if (this.operationIdNameMappings == null) {
this.operationIdNameMappings = new HashMap<>();
}
this.operationIdNameMappings.put(key, value);
return this;
}
/**
* Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together.
*
@@ -1389,7 +1346,6 @@ public final class GeneratorSettings implements Serializable {
Objects.equals(getParameterNameMappings(), that.getParameterNameMappings()) &&
Objects.equals(getModelNameMappings(), that.getModelNameMappings()) &&
Objects.equals(getEnumNameMappings(), that.getEnumNameMappings()) &&
Objects.equals(getOperationIdNameMappings(), that.getOperationIdNameMappings()) &&
Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) &&
Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) &&
Objects.equals(getOpenAPIGeneratorIgnoreList(), that.getOpenAPIGeneratorIgnoreList()) &&
@@ -1427,7 +1383,6 @@ public final class GeneratorSettings implements Serializable {
getParameterNameMappings(),
getModelNameMappings(),
getEnumNameMappings(),
getOperationIdNameMappings(),
getOpenAPINormalizer(),
getLanguageSpecificPrimitives(),
getOpenAPIGeneratorIgnoreList(),

View File

@@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=7.3.0
openApiGeneratorVersion=7.3.0-SNAPSHOT
# /RELEASE_VERSION
# BEGIN placeholders

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=7.3.0
openApiGeneratorVersion=7.3.0-SNAPSHOT
# /RELEASE_VERSION

View File

@@ -192,11 +192,6 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
*/
val enumNameMappings = project.objects.mapProperty<String, String>()
/**
* Specifies mappings between an operation id name and the new name
*/
val operationIdNameMappings = project.objects.mapProperty<String, String>()
/**
* Specifies mappings (rules) in OpenAPI normalizer
*/

View File

@@ -307,13 +307,6 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
@Input
val enumNameMappings = project.objects.mapProperty<String, String>()
/**
* Specifies mappings between the operation id name and the new name
*/
@Optional
@Input
val operationIdNameMappings = project.objects.mapProperty<String, String>()
/**
* Specifies mappings (rules) in OpenAPI normalizer
*/
@@ -879,12 +872,6 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
}
}
if (operationIdNameMappings.isPresent) {
operationIdNameMappings.get().forEach { entry ->
configurator.addOperationIdNameMapping(entry.key, entry.value)
}
}
if (openapiNormalizer.isPresent) {
openapiNormalizer.get().forEach { entry ->
configurator.addOpenAPINormalizer(entry.key, entry.value)

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -15,7 +15,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -19,7 +19,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<dependencies>
<dependency>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -20,7 +20,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -356,12 +356,6 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "enumNameMappings", property = "openapi.generator.maven.plugin.enumNameMappings")
private List<String> enumNameMappings;
/**
* A map of operation id names and the new names
*/
@Parameter(name = "operationIdNameMappings", property = "openapi.generator.maven.plugin.operationIdNameMappings")
private List<String> operationIdNameMappings;
/**
* A set of rules for OpenAPI normalizer
*/
@@ -863,11 +857,6 @@ public class CodeGenMojo extends AbstractMojo {
applyEnumNameMappingsKvpList(enumNameMappings, configurator);
}
// Apply Operation ID Name Mappings
if (operationIdNameMappings != null && (configOptions == null || !configOptions.containsKey("operation-id-name-mappings"))) {
applyOperationIdNameMappingsKvpList(operationIdNameMappings, configurator);
}
// Apply OpenAPI normalizer rules
if (openapiNormalizer != null && (configOptions == null || !configOptions.containsKey("openapi-normalizer"))) {
applyOpenAPINormalizerKvpList(openapiNormalizer, configurator);

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>7.3.0</version>
<version>7.3.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -158,8 +158,6 @@ public interface CodegenConfig {
Map<String, String> enumNameMapping();
Map<String, String> operationIdNameMapping();
Map<String, String> openapiNormalizer();
Map<String, String> apiTemplateFiles();

View File

@@ -51,11 +51,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public Set<String> oneOf = new TreeSet<>();
public Set<String> allOf = new TreeSet<>();
// The schema name as written in the OpenAPI document
// If it's a reserved word, it will be escaped.
// The schema name as written in the OpenAPI document.
public String name;
// The original schema name as written in the OpenAPI document.
public String schemaName;
// The language-specific name of the class that implements this schema.
// The name of the class is derived from the OpenAPI schema name with formatting rules applied.
// The classname is derived from the OpenAPI schema name, with sanitization and escaping rules applied.
@@ -495,15 +492,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
this.name = name;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public List<CodegenProperty> getOptionalVars() {
return optionalVars;
}
@@ -1156,7 +1144,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
Objects.equals(oneOf, that.oneOf) &&
Objects.equals(allOf, that.allOf) &&
Objects.equals(name, that.name) &&
Objects.equals(schemaName, that.schemaName) &&
Objects.equals(classname, that.classname) &&
Objects.equals(title, that.title) &&
Objects.equals(description, that.description) &&
@@ -1205,7 +1192,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
@Override
public int hashCode() {
return Objects.hash(getParent(), getParentSchema(), getInterfaces(), getAllParents(), getParentModel(),
getInterfaceModels(), getChildren(), anyOf, oneOf, allOf, getName(), getSchemaName(), getClassname(), getTitle(),
getInterfaceModels(), getChildren(), anyOf, oneOf, allOf, getName(), getClassname(), getTitle(),
getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(),
getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(),
getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble,
@@ -1227,7 +1214,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public String toString() {
final StringBuilder sb = new StringBuilder("CodegenModel{");
sb.append("name='").append(name).append('\'');
sb.append(", schemaName='").append(schemaName).append('\'');
sb.append(", parent='").append(parent).append('\'');
sb.append(", parentSchema='").append(parentSchema).append('\'');
sb.append(", interfaces=").append(interfaces);

View File

@@ -177,8 +177,6 @@ public class DefaultCodegen implements CodegenConfig {
protected Map<String, String> modelNameMapping = new HashMap<>();
// a map to store the mapping between enum name and the name provided by the user
protected Map<String, String> enumNameMapping = new HashMap<>();
// a map to store the mapping between operation id name and the name provided by the user
protected Map<String, String> operationIdNameMapping = new HashMap<>();
// a map to store the rules in OpenAPI Normalizer
protected Map<String, String> openapiNormalizer = new HashMap<>();
protected String modelPackage = "", apiPackage = "", fileSuffix;
@@ -667,16 +665,14 @@ public class DefaultCodegen implements CodegenConfig {
}
parent.getChildren().add(cm);
parent.hasChildren = true;
Schema parentSchema = this.openAPI.getComponents().getSchemas().get(parent.schemaName);
Schema parentSchema = this.openAPI.getComponents().getSchemas().get(parent.name);
if (parentSchema == null) {
LOGGER.warn("Failed to look up parent schema: {}", parent.schemaName);
parent = null;
throw new NullPointerException(parent.name + " in " + this.openAPI.getComponents().getSchemas());
}
if (parentSchema.getDiscriminator() == null) {
parent = allModels.get(parent.getParent());
} else {
if (parentSchema.getDiscriminator() == null) {
parent = allModels.get(parent.getParent());
} else {
parent = null;
}
parent = null;
}
}
}
@@ -1275,11 +1271,6 @@ public class DefaultCodegen implements CodegenConfig {
return enumNameMapping;
}
@Override
public Map<String, String> operationIdNameMapping() {
return operationIdNameMapping;
}
@Override
public Map<String, String> openapiNormalizer() {
return openapiNormalizer;
@@ -3124,7 +3115,6 @@ public class DefaultCodegen implements CodegenConfig {
} else {
m.name = name;
}
m.schemaName = name; // original schema name
m.title = escapeText(schema.getTitle());
m.description = escapeText(schema.getDescription());
m.unescapedDescription = schema.getDescription();
@@ -3763,7 +3753,7 @@ public class DefaultCodegen implements CodegenConfig {
for (String r : required) {
if (!properties.containsKey(r)) {
LOGGER.error("Required var {} not in properties", r);
LOGGER.error("Required var %s not in properties", r);
}
}
return;
@@ -4517,6 +4507,11 @@ public class DefaultCodegen implements CodegenConfig {
if (operation == null)
throw new RuntimeException("operation cannot be null in fromOperation");
if (operation.getExtensions() != null && Boolean.TRUE.equals(operation.getExtensions().get("x-internal"))) {
LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true",
httpMethod, path, operation.getOperationId());
}
Map<String, Schema> schemas = ModelUtils.getSchemas(this.openAPI);
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<>();
@@ -4561,11 +4556,7 @@ public class DefaultCodegen implements CodegenConfig {
op.path = path;
}
if (operationIdNameMapping.containsKey(operationId)) {
op.operationId = operationIdNameMapping.get(operationId);
} else {
op.operationId = toOperationId(operationId);
}
op.operationId = toOperationId(operationId);
op.summary = escapeText(operation.getSummary());
op.unescapedNotes = operation.getDescription();
op.notes = escapeText(operation.getDescription());
@@ -5092,31 +5083,25 @@ public class DefaultCodegen implements CodegenConfig {
String method = p.getKey();
Operation op = p.getValue();
if (op.getExtensions() != null && Boolean.TRUE.equals(op.getExtensions().get("x-internal"))) {
// skip operation if x-internal sets to true
LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true",
method, expression, op.getOperationId());
} else {
boolean genId = op.getOperationId() == null;
if (genId) {
op.setOperationId(getOrGenerateOperationId(op, c.name + "_" + expression.replaceAll("\\{\\$.*}", ""), method));
}
if (op.getExtensions() == null) {
op.setExtensions(new HashMap<>());
}
// This extension will be removed later by `fromOperation()` as it is only needed here to
// distinguish between normal operations and callback requests
op.getExtensions().put("x-callback-request", true);
CodegenOperation co = fromOperation(expression, method, op, servers);
if (genId) {
co.operationIdOriginal = null;
// legacy (see `fromOperation()`)
co.nickname = co.operationId;
}
u.requests.add(co);
boolean genId = op.getOperationId() == null;
if (genId) {
op.setOperationId(getOrGenerateOperationId(op, c.name + "_" + expression.replaceAll("\\{\\$.*}", ""), method));
}
if (op.getExtensions() == null) {
op.setExtensions(new HashMap<>());
}
// This extension will be removed later by `fromOperation()` as it is only needed here to
// distinguish between normal operations and callback requests
op.getExtensions().put("x-callback-request", true);
CodegenOperation co = fromOperation(expression, method, op, servers);
if (genId) {
co.operationIdOriginal = null;
// legacy (see `fromOperation()`)
co.nickname = co.operationId;
}
u.requests.add(co);
});
c.urls.add(u);
@@ -7373,20 +7358,7 @@ public class DefaultCodegen implements CodegenConfig {
}
protected void updateRequestBodyForMap(CodegenParameter codegenParameter, Schema schema, String name, Set<String> imports, String bodyParameterName) {
boolean useModel = true;
if (StringUtils.isBlank(name)) {
useModel = false;
} else {
if (ModelUtils.isFreeFormObject(schema)) {
useModel = ModelUtils.shouldGenerateFreeFormObjectModel(name, this);
} else if (ModelUtils.isMapSchema(schema)) {
useModel = ModelUtils.shouldGenerateMapModel(schema);
} else if (ModelUtils.isArraySchema(schema)) {
useModel = ModelUtils.shouldGenerateArrayModel(schema);
}
}
if (useModel) {
if (StringUtils.isNotBlank(name) && !(ModelUtils.isFreeFormObject(schema) && !ModelUtils.shouldGenerateFreeFormObjectModel(name, this))) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true);
} else {
Schema inner = ModelUtils.getAdditionalProperties(schema);

View File

@@ -517,13 +517,16 @@ public class DefaultGenerator implements Generator {
continue;
}
} else if (ModelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
if (!ModelUtils.shouldGenerateMapModel(schema)) {
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
// in the inner schemas, and the outer schema does not have properties.
if (!ModelUtils.isGenerateAliasAsModel(schema) && !ModelUtils.isComposedSchema(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to map
LOGGER.info("Model {} not generated since it's an alias to map (without property) and `generateAliasAsModel` is set to false (default)", name);
continue;
}
} else if (ModelUtils.isArraySchema(schema)) { // check to see if it's an "array" model
if (!ModelUtils.shouldGenerateArrayModel(schema)) {
if (!ModelUtils.isGenerateAliasAsModel(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to array
LOGGER.info("Model {} not generated since it's an alias to array (without property) and `generateAliasAsModel` is set to false (default)", name);
continue;
@@ -1492,36 +1495,31 @@ public class DefaultGenerator implements Generator {
final List<SecurityRequirement> globalSecurities = openAPI.getSecurity();
for (Tag tag : tags) {
try {
if (operation.getExtensions() != null && Boolean.TRUE.equals(operation.getExtensions().get("x-internal"))) {
// skip operation if x-internal sets to true
LOGGER.info("Operation ({} {} - {}) not generated since x-internal is set to true",
httpMethod, resourcePath, operation.getOperationId());
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, path.getServers());
codegenOperation.tags = new ArrayList<>(tags);
config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations);
List<SecurityRequirement> securities = operation.getSecurity();
if (securities != null && securities.isEmpty()) {
continue;
}
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities);
codegenOperation.hasAuthMethods = true;
} else {
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, path.getServers());
codegenOperation.tags = new ArrayList<>(tags);
config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations);
List<SecurityRequirement> securities = operation.getSecurity();
if (securities != null && securities.isEmpty()) {
continue;
}
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
authMethods = getAuthMethods(globalSecurities, securitySchemes);
if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, securities);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, globalSecurities);
codegenOperation.hasAuthMethods = true;
} else {
authMethods = getAuthMethods(globalSecurities, securitySchemes);
if (authMethods != null && !authMethods.isEmpty()) {
List<CodegenSecurity> fullAuthMethods = config.fromSecurity(authMethods);
codegenOperation.authMethods = filterAuthMethods(fullAuthMethods, globalSecurities);
codegenOperation.hasAuthMethods = true;
}
}
}
} catch (Exception ex) {
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
@@ -1532,6 +1530,7 @@ public class DefaultGenerator implements Generator {
throw new RuntimeException(msg, ex);
}
}
}
private static String generateParameterId(Parameter parameter) {

View File

@@ -612,8 +612,8 @@ public class InlineModelResolver {
Schema innerModel = modelFromProperty(openAPI, component, innerModelName);
// Recurse to create $refs for inner models
gatherInlineModels(innerModel, innerModelName);
String existing = matchGenerated(innerModel);
if (!skipAllOfInlineSchemas) {
String existing = matchGenerated(innerModel);
if (existing == null) {
innerModelName = addSchemas(innerModelName, innerModel);
Schema schema = new Schema().$ref(innerModelName);

View File

@@ -96,11 +96,6 @@ public class OpenAPINormalizer {
// when set to true, normalize OpenAPI 3.1 spec to make it work with the generator
final String NORMALIZE_31SPEC = "NORMALIZE_31SPEC";
// when set to true, remove x-internal: true from models, operations
final String REMOVE_X_INTERNAL = "REMOVE_X_INTERNAL";
final String X_INTERNAL = "x-internal";
boolean removeXInternal;
// ============= end of rules =============
/**
@@ -130,7 +125,6 @@ public class OpenAPINormalizer {
ruleNames.add(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE);
ruleNames.add(REFACTOR_ALLOF_WITH_PROPERTIES_ONLY);
ruleNames.add(NORMALIZE_31SPEC);
ruleNames.add(REMOVE_X_INTERNAL);
// rules that are default to true
rules.put(SIMPLIFY_ONEOF_ANYOF, true);
@@ -230,6 +224,7 @@ public class OpenAPINormalizer {
normalizeParameters(path.getParameters());
for (Operation operation : operations) {
normalizeOperation(operation);
normalizeRequestBody(operation);
normalizeParameters(operation.getParameters());
@@ -244,8 +239,6 @@ public class OpenAPINormalizer {
* @param operation Operation
*/
private void normalizeOperation(Operation operation) {
processRemoveXInternalFromOperation(operation);
processKeepOnlyFirstTagInOperation(operation);
processSetTagsForAllOperations(operation);
@@ -379,15 +372,8 @@ public class OpenAPINormalizer {
if (schema == null) {
LOGGER.warn("{} not fount found in openapi/components/schemas.", schemaName);
} else {
// remove x-internal if needed
if (schema.getExtensions() != null && getRule(REMOVE_X_INTERNAL)) {
if (Boolean.parseBoolean(String.valueOf(schema.getExtensions().get(X_INTERNAL)))) {
schema.getExtensions().remove(X_INTERNAL);
}
}
// normalize the schemas
schemas.put(schemaName, normalizeSchema(schema, new HashSet<>()));
Schema result = normalizeSchema(schema, new HashSet<>());
schemas.put(schemaName, result);
}
}
}
@@ -619,26 +605,6 @@ public class OpenAPINormalizer {
}
}
/**
* Keep only first tag in the operation if the operation has more than
* one tag.
*
* @param operation Operation
*/
private void processRemoveXInternalFromOperation(Operation operation) {
if (!getRule(REMOVE_X_INTERNAL)) {
return;
}
if (operation.getExtensions() == null) {
return;
}
if (Boolean.parseBoolean(String.valueOf(operation.getExtensions().get("x-internal")))) {
operation.getExtensions().remove(X_INTERNAL);
}
}
/**
* Keep only first tag in the operation if the operation has more than
* one tag.
@@ -772,15 +738,11 @@ public class OpenAPINormalizer {
*
* @param schema Schema
*/
public boolean isNullTypeSchema(Schema schema) {
private boolean isNullTypeSchema(Schema schema) {
if (schema == null) {
return true;
}
if (ModelUtils.hasAllOf(schema) || ModelUtils.hasOneOf(schema) || ModelUtils.hasAnyOf(schema)) {
return false;
}
if (schema.getTypes() != null && !schema.getTypes().isEmpty()) {
// 3.1 spec
if (schema.getTypes().size() ==1) { // 1 type only
@@ -791,7 +753,7 @@ public class OpenAPINormalizer {
}
}
if (!(schema instanceof JsonSchema) && (schema.getType() == null || schema.getType().equals("null")) && schema.get$ref() == null) {
if ((schema.getType() == null || schema.getType().equals("null")) && schema.get$ref() == null) {
return true;
}

View File

@@ -75,7 +75,6 @@ public class CodegenConfigurator {
private Map<String, String> parameterNameMappings = new HashMap<>();
private Map<String, String> modelNameMappings = new HashMap<>();
private Map<String, String> enumNameMappings = new HashMap<>();
private Map<String, String> operationIdNameMappings = new HashMap<>();
private Map<String, String> openapiNormalizer = new HashMap<>();
private Set<String> languageSpecificPrimitives = new HashSet<>();
private Set<String> openapiGeneratorIgnoreList = new HashSet<>();
@@ -142,9 +141,6 @@ public class CodegenConfigurator {
if(generatorSettings.getEnumNameMappings() != null) {
configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings());
}
if(generatorSettings.getOperationIdNameMappings() != null) {
configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings());
}
if(generatorSettings.getOpenAPINormalizer() != null) {
configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer());
}
@@ -262,12 +258,6 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator addOperationIdNameMapping(String key, String value) {
this.operationIdNameMappings.put(key, value);
generatorSettingsBuilder.withOperationIdNameMapping(key, value);
return this;
}
public CodegenConfigurator addOpenAPINormalizer(String key, String value) {
this.openapiNormalizer.put(key, value);
generatorSettingsBuilder.withOpenAPINormalizer(key, value);
@@ -476,12 +466,6 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator setOperationIdNameMappings(Map<String, String> operationIdNameMappings) {
this.operationIdNameMappings = operationIdNameMappings;
generatorSettingsBuilder.withOperationIdNameMappings(operationIdNameMappings);
return this;
}
public CodegenConfigurator setOpenAPINormalizer(Map<String, String> openapiNormalizer) {
this.openapiNormalizer = openapiNormalizer;
generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer);
@@ -778,7 +762,6 @@ public class CodegenConfigurator {
config.parameterNameMapping().putAll(generatorSettings.getParameterNameMappings());
config.modelNameMapping().putAll(generatorSettings.getModelNameMappings());
config.enumNameMapping().putAll(generatorSettings.getEnumNameMappings());
config.operationIdNameMapping().putAll(generatorSettings.getOperationIdNameMappings());
config.openapiNormalizer().putAll(generatorSettings.getOpenAPINormalizer());
config.languageSpecificPrimitives().addAll(generatorSettings.getLanguageSpecificPrimitives());
config.openapiGeneratorIgnoreList().addAll(generatorSettings.getOpenAPIGeneratorIgnoreList());

View File

@@ -172,19 +172,6 @@ public final class CodegenConfiguratorUtils {
}
}
public static void applyOperationIdNameMappingsKvpList(List<String> operationIdNameMappings, CodegenConfigurator configurator) {
for (String propString : operationIdNameMappings) {
applyOperationIdNameMappingsKvp(propString, configurator);
}
}
public static void applyOperationIdNameMappingsKvp(String operationIdNameMappings, CodegenConfigurator configurator) {
final Map<String, String> map = createMapFromKeyValuePairs(operationIdNameMappings);
for (Map.Entry<String, String> entry : map.entrySet()) {
configurator.addOperationIdNameMapping(entry.getKey().trim(), entry.getValue().trim());
}
}
public static void applyOpenAPINormalizerKvpList(List<String> openapiNormalizer, CodegenConfigurator configurator) {
for (String propString : openapiNormalizer) {
applyOpenAPINormalizerKvp(propString, configurator);

View File

@@ -1003,21 +1003,21 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (items.getMinimum() != null && items.getMaximum() != null) {
return String.format(Locale.ROOT, "@DecimalMin(value = \"%s\", inclusive = %s) @DecimalMax(value = \"%s\", inclusive = %s)",
items.getMinimum(),
!Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE),
Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE),
items.getMaximum(),
!Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE));
Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE));
}
if (items.getMinimum() != null) {
return String.format(Locale.ROOT, "@DecimalMin( value = \"%s\", inclusive = %s)",
items.getMinimum(),
!Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE));
Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE));
}
if (items.getMaximum() != null) {
return String.format(Locale.ROOT, "@DecimalMax( value = \"%s\", inclusive = %s)",
items.getMaximum(),
!Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE));
Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE));
}
return "";
@@ -1289,9 +1289,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return localDate.toString();
}
if (ModelUtils.isArraySchema(schema)) {
// swagger-parser parses the default value differently depending on whether it's in a referenced file or not.
// cf. https://github.com/swagger-api/swagger-parser/issues/1958
// ArrayList if in the referenced file, ArrayNode if not.
if (defaultValue instanceof ArrayNode) {
ArrayNode array = (ArrayNode) defaultValue;
return StreamSupport.stream(array.spliterator(), false)
@@ -1300,11 +1297,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
.map(item -> StringUtils.removeStart(item, "\""))
.map(item -> StringUtils.removeEnd(item, "\""))
.collect(Collectors.joining(","));
} else if (defaultValue instanceof ArrayList) {
ArrayList<?> array = (ArrayList<?>) defaultValue;
return array.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
}
}
// escape quotes

View File

@@ -937,7 +937,7 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
if (!model.allOf.isEmpty()) { // allOf
for (CodegenProperty cp : model.allVars) {
if (!cp.isPrimitiveType || cp.isModel) {
if (cp.isArray || cp.isMap){ // if array or map
if (cp.isArray){ // if array
modelImports.add(cp.items.dataType);
}else{ // if model
modelImports.add(cp.getDataType());
@@ -1244,11 +1244,11 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
if (!StringUtils.isEmpty(operation.returnType)) {
// Not interested in the result, only in the update of the imports
getPydanticType(
operation.returnProperty,
operation.returnProperty,
modelImports,
exampleImports,
exampleImports,
postponedModelImports,
postponedExampleImports,
postponedExampleImports,
null
);
}
@@ -1271,7 +1271,7 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
}
operation.vendorExtensions.put("x-py-example-import", imports);
}
// Remove constant params from allParams list and add to constantParams
handleConstantParams(operation);
}

View File

@@ -889,7 +889,7 @@ public abstract class AbstractPythonPydanticV1Codegen extends DefaultCodegen imp
if (!model.allOf.isEmpty()) { // allOf
for (CodegenProperty cp : model.allVars) {
if (!cp.isPrimitiveType || cp.isModel) {
if (cp.isArray || cp.isMap){ // if array or map
if (cp.isArray){ // if array
modelImports.add(cp.items.dataType);
}else{ // if model
modelImports.add(cp.dataType);

View File

@@ -129,9 +129,6 @@ public abstract class CppQtAbstractCodegen extends AbstractCppCodegen implements
systemIncludes.add("QDate");
systemIncludes.add("QDateTime");
systemIncludes.add("QByteArray");
reservedWords.add("signals");
reservedWords.add("slots");
}
@Override

View File

@@ -120,9 +120,6 @@ public class CppQtClientCodegen extends CppQtAbstractCodegen implements CodegenC
typeMapping.put("AnyType", "QJsonValue");
importMapping.put(PREFIX + "HttpFileElement", "#include \"" + PREFIX + "HttpFileElement.h\"");
importMapping.put("QJsonValue", "#include <QJsonValue>");
reservedWords.add("valid");
reservedWords.add("set");
}
@Override

View File

@@ -500,9 +500,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
}
if (model.hasRequired) {
if (!model.isAdditionalPropertiesTrue &&
(model.oneOf == null || model.oneOf.isEmpty()) &&
(model.anyOf == null || model.anyOf.isEmpty())) {
if (!model.isAdditionalPropertiesTrue) {
imports.add(createMapping("import", "bytes"));
}

View File

@@ -99,12 +99,6 @@ public class PhpDataTransferClientCodegen extends AbstractPhpCodegen {
// remove these from primitive types to make the output works
languageSpecificPrimitives.remove("\\DateTime");
languageSpecificPrimitives.remove("\\SplFileObject");
// fix date and date-time mapping to support both DateTime and DateTimeImmutable
typeMapping.put("date", "\\DateTimeInterface");
typeMapping.put("Date", "\\DateTimeInterface");
typeMapping.put("DateTime", "\\DateTimeInterface");
// TODO provide proper support for "file" string format
typeMapping.put("file", "string");
apiTemplateFiles.clear();
apiTestTemplateFiles.clear();
@@ -114,7 +108,7 @@ public class PhpDataTransferClientCodegen extends AbstractPhpCodegen {
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0");
//Register custom CLI options
addSwitch(OPT_MODERN, "use modern language features (generated code will require PHP 8.1)", useModernSyntax);
addSwitch(OPT_MODERN, "use modern language features (generated code will require PHP 8.0)", useModernSyntax);
}
@Override
@@ -159,26 +153,13 @@ public class PhpDataTransferClientCodegen extends AbstractPhpCodegen {
return super.toApiName(toModelName(name));
}
@Override
public String toRegularExpression(String pattern) {
String result = super.toRegularExpression(pattern);
if ((result != null) && (!useModernSyntax)) {
//Doctrine Annotations have different string escape rules compared to PHP code
result = result
.replace("\\\\", "\\")
.replace("\\\"", "\"\"")
;
}
return result;
}
@Override
public String getTypeDeclaration(Schema p) {
String result;
Map<String, Object> extensions = p.getExtensions();
if ((extensions != null) && extensions.containsKey(VEN_CONTAINER_DATA_TYPE)) {
result = (String) extensions.get(VEN_CONTAINER_DATA_TYPE);
} else if (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p)) {
} else if (useModernSyntax && (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p))) {
result = "array";
} else {
result = super.getTypeDeclaration(p);

View File

@@ -226,11 +226,6 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
for (ModelMap mo : models) {
CodegenModel cm = mo.getModel();
// Type is already any
if (cm.getAdditionalPropertiesIsAnyType() && "any".equals(cm.getAdditionalPropertiesType())) {
cm.setAdditionalPropertiesIsAnyType(false);
}
// Deduce the model file name in kebab case
cm.classFilename = cm.classname.replaceAll("([a-z0-9])([A-Z])", "$1-$2").toLowerCase(Locale.ROOT);

View File

@@ -884,17 +884,6 @@ public class ModelUtils {
return unaliasedSchema.get$ref() != null;
}
public static boolean shouldGenerateMapModel(Schema schema) {
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
// in the inner schemas, and the outer schema does not have properties.
return ModelUtils.isGenerateAliasAsModel(schema) || ModelUtils.isComposedSchema(schema) || !(schema.getProperties() == null || schema.getProperties().isEmpty());
}
public static boolean shouldGenerateArrayModel(Schema schema) {
return ModelUtils.isGenerateAliasAsModel(schema) || !(schema.getProperties() == null || schema.getProperties().isEmpty());
}
/**
* If a Schema contains a reference to another Schema with '$ref', returns the referenced Schema if it is found or the actual Schema in the other cases.
*

View File

@@ -534,12 +534,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
JsonElement jsonElement = gson.toJsonTree(entry.getValue());
if (jsonElement.isJsonArray()) {
obj.add(entry.getKey(), jsonElement.getAsJsonArray());
} else {
obj.add(entry.getKey(), jsonElement.getAsJsonObject());
}
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}

View File

@@ -313,23 +313,6 @@
<version>${jodatime-version}</version>
</dependency>
{{/joda}}
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>${beanvalidation-version}</version>
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{#performBeanValidation}}
<!-- Bean Validation Impl. used to perform BeanValidation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator-version}</version>
</dependency>
{{/performBeanValidation}}
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
@@ -373,12 +356,6 @@
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}
{{#useBeanValidation}}
<beanvalidation-version>2.0.2</beanvalidation-version>
{{/useBeanValidation}}
{{#performBeanValidation}}
<hibernate-validator-version>5.4.3.Final</hibernate-validator-version>
{{/performBeanValidation}}
<junit-version>4.13.2</junit-version>
</properties>
</project>

View File

@@ -11,7 +11,6 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
{{#imports}}import {{import}};
@@ -80,11 +79,7 @@ public class {{classname}} {
@ApiResponse(responseCode = "{{{code}}}", description = "{{{message}}}", content =
@Content(schema = @Schema(implementation = {{{baseType}}}.class))),
{{/responses}}
}{{#hasAuthMethods}},security = {
{{#authMethods}}
@SecurityRequirement(name = "{{name}}"{{#scopes.0}}, scopes={ {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} }{{/scopes.0}}){{^-last}},{{/-last}}
{{/authMethods}}
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} })
}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} })
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.{{nickname}}({{#allParams}}{{#isFormParam}}{{#isFile}}{{paramName}}Bodypart{{/isFile}}{{/isFormParam}}{{^isFile}}{{paramName}}{{/isFile}}{{^isFormParam}}{{#isFile}}{{paramName}}{{/isFile}}{{/isFormParam}}, {{/allParams}}securityContext);

View File

@@ -64,7 +64,7 @@ class {{classname}} {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}}e
{{#-first}}
// check to make sure all required properties are present in the JSON string
for (const property of {{classname}}.RequiredProperties) {
if (!data.hasOwnProperty(property)) {
if (!data[property]) {
throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data));
}
}

View File

@@ -2,9 +2,6 @@ cmake_minimum_required(VERSION 3.5)
project({{{packageName}}})
set(CMAKE_AUTOMOC ON)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Network Gui)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Network Gui)
include(GNUInstallDirs)

View File

@@ -21,11 +21,7 @@ type Route struct {
// NewRouter returns a new router.
func NewRouter(handleFunctions ApiHandleFunctions) *gin.Engine {
return NewRouterWithGinEngine(gin.Default(), handleFunctions)
}
// NewRouter add routes to existing gin engine.
func NewRouterWithGinEngine(router *gin.Engine, handleFunctions ApiHandleFunctions) *gin.Engine {
router := gin.Default()
for _, route := range getRoutes(handleFunctions) {
if route.HandlerFunc == nil {
route.HandlerFunc = DefaultHandleFunc

View File

@@ -311,7 +311,7 @@ func NewNullableTime(val *time.Time) *NullableTime {
}
func (v NullableTime) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
return v.value.MarshalJSON()
}
func (v *NullableTime) UnmarshalJSON(src []byte) error {

View File

@@ -19,8 +19,6 @@ public class RestConfiguration extends RouteBuilder {
.component("{{camelRestComponent}}")
.bindingMode(RestBindingMode.{{camelRestBindingMode}}){{#camelDataformatProperties}}
.dataFormatProperty("{{key}}", "{{value}}"){{/camelDataformatProperties}}
.clientRequestValidation({{camelRestClientRequestValidation}})
.apiProperty("api.title", "{{appName}}")
.apiProperty("api.version", "{{appVersion}}");
.clientRequestValidation({{camelRestClientRequestValidation}});
}
}
}

View File

@@ -44,17 +44,7 @@ class ApiClient extends OAGAC\AbstractApiClient
$request = $this->addCookies($request, $parameters);
{{/cookieParams.0}}
{{#bodyParam}}
{{#isDate}}
$request = $this->addBody($request, $requestMediaType, $requestContent, ($this->contentStrategies)('Date', []));
{{/isDate}}
{{#isDateTime}}
$request = $this->addBody($request, $requestMediaType, $requestContent, ($this->contentStrategies)('DateTime', []));
{{/isDateTime}}
{{^isDate}}
{{^isDateTime}}
$request = $this->addBody($request, $requestMediaType, $requestContent);
{{/isDateTime}}
{{/isDate}}
{{/bodyParam}}
{{#hasProduces}}
$request = $this->addAcceptHeader($request, $responseMediaType);
@@ -78,8 +68,6 @@ class ApiClient extends OAGAC\AbstractApiClient
{
$response = $this->{{operationId}}Raw({{>api_arg_call}});
$responseContent = null;
$contentStrategy = null;
$contentValidator = null;
switch ($response->getStatusCode())
{
{{#responses}}
@@ -87,35 +75,25 @@ class ApiClient extends OAGAC\AbstractApiClient
{{#message}}
/* {{&message}} */
{{/message}}
{{#isArray}}
$responseContent = new {{dataType}}();
{{/isArray}}
{{#isMap}}
$responseContent = new {{dataType}}();
{{/isMap}}
{{#isDate}}
$contentStrategy = ($this->contentStrategies)('Date', []);
$contentValidator = ($this->contentValidators)('Date', []);
{{/isDate}}
{{#isDateTime}}
$contentStrategy = ($this->contentStrategies)('DateTime', []);
$contentValidator = ($this->contentValidators)('DateTime', []);
{{/isDateTime}}
{{^isDate}}
{{^isDateTime}}
{{^isArray}}
{{^isMap}}
{{#isModel}}
$responseContent = new {{dataType}}();
{{/isModel}}
{{^isModel}}
{{#isArray}}
$responseContent = new {{dataType}}();
{{/isArray}}
{{/isModel}}
{{^isModel}}
{{^isArray}}
{{#isMap}}
$responseContent = new {{dataType}}();
{{/isMap}}
{{/isArray}}
{{/isDateTime}}
{{/isDate}}
{{/isModel}}
break;
{{/responses}}
}
$this->parseBody($response, $responseContent, $contentStrategy, $contentValidator);
$this->parseBody($response, $responseContent);
return [$responseContent, $response->getHeaders(), $response->getStatusCode(), $response->getReasonPhrase()];
}

View File

@@ -3,20 +3,18 @@ declare(strict_types=1);
namespace {{invokerPackage}};
use Articus\PluginManager as PM;
use Articus\DataTransfer as DT;
use Interop\Container\ContainerInterface;
use OpenAPIGenerator\APIClient as OAGAC;
use Psr\Container\ContainerInterface;
class ApiClientFactory implements PM\ServiceFactoryInterface
class ApiClientFactory extends DT\ConfigAwareFactory
{
use PM\ConfigAwareFactoryTrait;
public function __construct(string $configKey = ApiClient::class)
{
$this->configKey = $configKey;
parent::__construct($configKey);
}
public function __invoke(ContainerInterface $container, $requestedName, array $options = null): ApiClient
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = new OAGAC\ApiClientOptions(\array_merge($this->getServiceConfig($container), $options ?? []));
return new ApiClient(
@@ -26,9 +24,7 @@ class ApiClientFactory implements PM\ServiceFactoryInterface
$container->get($config->httpClientServiceName),
$container->get($config->securityProviderFactoryServiceName),
$container->get($config->bodyCoderFactoryServiceName),
$container->get($config->bodyCoderFactoryServiceName),
$container->get($config->contentStrategyFactoryServiceName),
$container->get($config->contentValidatorFactoryServiceName)
$container->get($config->bodyCoderFactoryServiceName)
);
}
}

View File

@@ -5,8 +5,8 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project.
## Overview
This lightweight extensible client library is [PSR-7](https://www.php-fig.org/psr/psr-7), [PSR-11](https://www.php-fig.org/psr/psr-11), [PSR-17](https://www.php-fig.org/psr/psr-17) and [PSR-18](https://www.php-fig.org/psr/psr-18) complaint and relies on:
- PHP: >=8.1
- [Data Transfer](https://github.com/Articus/DataTransfer): >=0.6
- PHP: >=8.0
- [Data Transfer](https://github.com/Articus/DataTransfer): >=0.5
## How to use
@@ -21,7 +21,7 @@ Then check content types for API requests you intend to send and API responses y
After that review security requirements for API operations you intend to use. For each unique security scheme you will need an implementation of [OpenAPIGenerator\APIClient\SecurityProviderInterface](https://github.com/Articus/OpenAPIGeneratorAPIClient-PHP/blob/master/src/OpenAPIGenerator/APIClient/SecurityProviderInterface.php). Currently, only [HTTP Bearer authentication](https://github.com/Articus/OpenAPIGeneratorAPIClient-PHP/blob/master/src/OpenAPIGenerator/APIClient/SecurityProvider/HttpBearer.php) is supported out-of-the-box.
The last step is to configure and wire all services together. It is highly advisable to use [PSR-11 container](https://packagist.org/packages/psr/container) for that. If you have not selected one for your project yet, https://packagist.org/providers/psr/container-implementation may help to find some suitable options. Here is a sample wiring configuration for `"laminas/laminas-servicemanager"`, `"nyholm/psr7"` and `"symfony/http-client"` (consult generated `composer.json` for the exact versions of used packages):
The last step is to configure and wire all services together. It is highly advisable to use [PSR-11 container](https://packagist.org/packages/psr/container) for that. If you have not selected one for your project yet, https://packagist.org/providers/psr/container-implementation may help to find some suitable options. Here is a sample wiring configuration for `"laminas/laminas-servicemanager"`, `"laminas/laminas-diactoros"` and `"symfony/http-client"` (consult generated `composer.json` for the exact versions of used packages):
```PHP
<?php
@@ -31,24 +31,21 @@ require_once __DIR__ . '/vendor/autoload.php';
$dependencies = [
'invokables' => [
Psr\Http\Message\RequestFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\ResponseFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\StreamFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\RequestFactoryInterface::class => Laminas\Diactoros\RequestFactory::class,
Psr\Http\Message\ResponseFactoryInterface::class => Laminas\Diactoros\ResponseFactory::class,
Psr\Http\Message\StreamFactoryInterface::class => Laminas\Diactoros\StreamFactory::class,
],
'factories' => [
{{invokerPackage}}\ApiClient::class => {{invokerPackage}}\ApiClientFactory::class,
Articus\DataTransfer\Service::class => Articus\DataTransfer\Factory::class,
Articus\DataTransfer\MetadataProvider\PhpAttribute::class => Articus\DataTransfer\MetadataProvider\Factory\PhpAttribute::class,
Articus\DataTransfer\Options::DEFAULT_STRATEGY_PLUGIN_MANAGER => [Articus\PluginManager\Factory\Chain::class, 'app_dt_strategy_manager_chain'],
'oas_dt_strategy_manager' => OpenAPIGenerator\Common\Strategy\Factory\PluginManager::class,
'app_dt_strategy_manager' => Articus\DataTransfer\Strategy\Factory\SimplePluginManager::class,
Articus\DataTransfer\Options::DEFAULT_VALIDATOR_PLUGIN_MANAGER => [Articus\PluginManager\Factory\Chain::class, 'app_dt_validator_manager_chain'],
'oas_dt_validator_manager' => OpenAPIGenerator\Common\Validator\Factory\PluginManager::class,
'app_dt_validator_manager' => Articus\DataTransfer\Validator\Factory\SimplePluginManager::class,
Articus\DataTransfer\Strategy\PluginManager::class => Articus\DataTransfer\Strategy\Factory\PluginManager::class,
Articus\DataTransfer\Validator\PluginManager::class => Articus\DataTransfer\Validator\Factory\PluginManager::class,
Laminas\Validator\ValidatorPluginManager::class => Laminas\Validator\ValidatorPluginManagerFactory::class,
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_BODY_CODER_PLUGIN_MANAGER => OpenAPIGenerator\APIClient\BodyCoder\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER => OpenAPIGenerator\APIClient\SecurityProvider\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class => OpenAPIGenerator\APIClient\SecurityProvider\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\BodyCoder\PluginManager::class => OpenAPIGenerator\APIClient\BodyCoder\Factory\PluginManager::class,
Psr\Http\Client\ClientInterface::class => function (Psr\Container\ContainerInterface $container)
{
@@ -67,17 +64,34 @@ $dependencies = [
$config = [
'dependencies' => $dependencies,
//Configure DataTransfer library: add pack of extra strategies and pack of extra validators
'app_dt_strategy_manager_chain' => [
'managers' => [
'oas_dt_strategy_manager',
'app_dt_strategy_manager',
//Configure DataTransfer library
Articus\DataTransfer\Strategy\PluginManager::class => [
'invokables' => [
'QueryStringScalar' => OpenAPIGenerator\Common\Strategy\QueryStringScalar::class,
'QueryStringScalarArray' => OpenAPIGenerator\Common\Strategy\QueryStringScalarArray::class,
],
'factories' => [
'Date' => OpenAPIGenerator\Common\Strategy\Factory\ImmutableDate::class,
'DateTime' => OpenAPIGenerator\Common\Strategy\Factory\ImmutableDateTime::class,
'ObjectList' => OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList::class,
'ObjectMap' => OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap::class,
'ScalarList' => OpenAPIGenerator\Common\Strategy\Factory\ScalarList::class,
'ScalarMap' => OpenAPIGenerator\Common\Strategy\Factory\ScalarMap::class,
]
],
Articus\DataTransfer\Validator\PluginManager::class => [
'invokables' => [
'Scalar' => OpenAPIGenerator\Common\Validator\Scalar::class,
'QueryStringScalar' => OpenAPIGenerator\Common\Validator\QueryStringScalar::class,
'QueryStringScalarArray' => OpenAPIGenerator\Common\Validator\QueryStringScalarArray::class,
],
'abstract_factories' => [
Articus\DataTransfer\Validator\Factory\Laminas::class,
],
],
'app_dt_validator_manager_chain' => [
'managers' => [
'oas_dt_validator_manager',
'app_dt_validator_manager',
'validators' => [
'invokables' => [
'Count' => Laminas\Validator\IsCountable::class,
],
],
@@ -87,19 +101,19 @@ $config = [
],
//Register body coders for used content types here
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_BODY_CODER_PLUGIN_MANAGER => [
OpenAPIGenerator\APIClient\BodyCoder\PluginManager::class => [
'factories' => [
//'another/mime-type' => AnotherMimeTypeBodyCoder::class
],
],
//Register security providers for used security schemes here
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER => [
OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class => [
'factories' => [
//'another-security-scheme' => AnotherSecuritySchemeProvider::class,
],
'aliases' => [
//'custom-name-for-http-bearer' => OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class,
//'custom-name-for-htt-bearer' => OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class,
],
],
];
@@ -112,10 +126,10 @@ $client = $container->get({{invokerPackage}}\ApiClient::class);
//... and now you can use client methods to call API operations :)
//And one more sample: how to set token for HTTP Bearer authentication
/** @var Articus\PluginManager\PluginManagerInterface $securityProviders */
$securityProviders = $container->get(OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER);
/** @var OpenAPIGenerator\APIClient\SecurityProvider\PluginManager $securityProviders */
$securityProviders = $container->get(OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class);
/** @var OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer $httpBearer */
$httpBearer = $securityProviders(OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class, []);
$httpBearer = $securityProviders->get(OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class);
$httpBearer->setToken('some-token');
```

View File

@@ -13,7 +13,7 @@
* @param {{dataType}} $requestContent
{{/bodyParam}}
{{#hasAuthMethods}}
* @param iterable<string, string[]> $security
* @param iterable|string[][] $security
{{/hasAuthMethods}}
{{#hasConsumes}}
* @param string $requestMediaType

View File

@@ -1,6 +1,8 @@
{
"name": "{{#lambda.lowercase}}{{gitUserId}}/{{gitRepoId}}{{/lambda.lowercase}}",
"description": "{{description}}",
"version": "{{artifactVersion}}",
"type": "library",
"keywords": [
"openapi",
"php",
@@ -15,15 +17,14 @@
"homepage": "{{{developerOrganizationUrl}}}"
}
],
"version": "{{artifactVersion}}",
"type": "library",
"require": {
"php": "^8.1",
"articus/data-transfer": "^0.6",
"articus/openapi-generator-common": "^0.3",
"articus/openapi-generator-apiclient": "^0.2",
"php": "^8.0",
"articus/data-transfer": "^0.5",
"articus/openapi-generator-common": "^0.2",
"articus/openapi-generator-apiclient": "^0.1",
"psr/simple-cache": "^1.0",
"laminas/laminas-stdlib": "^3.18"
"laminas/laminas-stdlib": "^3.2",
"laminas/laminas-validator": "^2.13"
},
"autoload": {
"psr-4": {
@@ -31,8 +32,8 @@
}
},
"require-dev": {
"laminas/laminas-servicemanager": "^3.22",
"nyholm/psr7": "^1.8",
"symfony/http-client": "^6.4 || ^7.0"
"laminas/laminas-servicemanager": "^3.6",
"laminas/laminas-diactoros": "^2.6",
"symfony/http-client": "^5.3"
}
}

View File

@@ -1,18 +1,7 @@
{{#vars
}}{{#isArray
}}{{#isPrimitiveType
}}#[DTA\Strategy("ScalarList", ["type" => {{>list_item_type}}])]
{{/isPrimitiveType
}}{{#items.isDate
}}#[DTA\Strategy("DateList")]
{{/items.isDate
}}{{#items.isDateTime
}}#[DTA\Strategy("DateTimeList")]
{{/items.isDateTime
}}{{^isPrimitiveType}}{{^items.isDate}}{{^items.isDateTime
}}#[DTA\Strategy("ObjectList", ["type" => {{>list_item_type}}])]
{{/items.isDateTime}}{{/items.isDate}}{{/isPrimitiveType
}}{{#minItems}}{{^maxItems
}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", ["type" => {{>list_item_type}}])]
{{#minItems}}{{^maxItems
}}#[DTA\Validator("Count", ["min" => {{minItems}}], blocker: true)]
{{/maxItems}}{{/minItems
}}{{^minItems}}{{#maxItems
@@ -25,31 +14,20 @@
{{#isPrimitiveType
}} ["name" => "Scalar", "options" => ["type" => {{>list_item_type}}]]
{{/isPrimitiveType
}}{{#items.isDate
}}{{#isDate
}} ["name" => "Date"]
{{/items.isDate
}}{{#items.isDateTime
}} ["name" => "DateTime"]
{{/items.isDateTime
}}{{^isPrimitiveType}}{{^items.isDate}}{{^items.isDateTime
{{/isDate
}}{{#isDateTime
}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]]
{{/isDateTime
}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime
}} ["name" => "TypeCompliant", "options" => ["type" => {{>list_item_type}}]]
{{/items.isDateTime}}{{/items.isDate}}{{/isPrimitiveType
{{/isDateTime}}{{/isDate}}{{/isPrimitiveType
}}]])]
{{/isArray
}}{{#isMap
}}{{#isPrimitiveType
}}#[DTA\Strategy("ScalarMap", ["type" => {{>map_item_type}}])]
{{/isPrimitiveType
}}{{#additionalProperties.isDate
}}#[DTA\Strategy("DateMap")]
{{/additionalProperties.isDate
}}{{#additionalProperties.isDateTime
}}#[DTA\Strategy("DateTimeMap")]
{{/additionalProperties.isDateTime
}}{{^isPrimitiveType}}{{^additionalProperties.isDate}}{{^additionalProperties.isDateTime
}}#[DTA\Strategy("ObjectMap", ["type" => {{>map_item_type}}])]
{{/additionalProperties.isDateTime}}{{/additionalProperties.isDate}}{{/isPrimitiveType
}}{{#minProperties}}{{^maxProperties
}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", ["type" => {{>map_item_type}}])]
{{#minProperties}}{{^maxProperties
}}#[DTA\Validator("Count", ["min" => {{minProperties}}], blocker: true)]
{{/maxProperties}}{{/minProperties
}}{{^minProperties}}{{#maxProperties
@@ -62,15 +40,15 @@
{{#isPrimitiveType
}} ["name" => "Scalar", "options" => ["type" => {{>map_item_type}}]]
{{/isPrimitiveType
}}{{#additionalProperties.isDate
}}{{#isDate
}} ["name" => "Date"]
{{/additionalProperties.isDate
}}{{#additionalProperties.isDateTime
}} ["name" => "DateTime"]
{{/additionalProperties.isDateTime
}}{{^isPrimitiveType}}{{^additionalProperties.isDate}}{{^additionalProperties.isDateTime
{{/isDate
}}{{#isDateTime
}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]]
{{/isDateTime
}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime
}} ["name" => "TypeCompliant", "options" => ["type" => {{>map_item_type}}]]
{{/additionalProperties.isDateTime}}{{/additionalProperties.isDate}}{{/isPrimitiveType
{{/isDateTime}}{{/isDate}}{{/isPrimitiveType
}}]])]
{{/isMap
}}{{/vars

View File

@@ -12,7 +12,7 @@
{{/isDate
}}{{#isDateTime
}} #[DTA\Strategy("DateTime")]
#[DTA\Validator("DateTime")]
#[DTA\Validator("Date", ["format" => \DateTime::RFC3339])]
{{/isDateTime
}}{{^isPrimitiveType
}}{{^isDate
@@ -25,24 +25,21 @@
}}{{/isContainer
}}{{#hasValidation
}}{{#minLength}}{{#maxLength
}} #[DTA\Validator("Length", ["min" => {{minLength}}, "max" => {{maxLength}}])]
}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}])]
{{/maxLength}}{{/minLength
}}{{^minLength}}{{#maxLength
}} #[DTA\Validator("Length", ["max" => {{maxLength}}])]
}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}])]
{{/maxLength}}{{/minLength
}}{{#minLength}}{{^maxLength
}} #[DTA\Validator("Length", ["min" => {{minLength}}])]
}} #[DTA\Validator("StringLength", ["min" => {{minLength}}])]
{{/maxLength}}{{/minLength
}}{{#minimum}}{{#maximum
}} #[DTA\Validator("Range", ["min" => {{minimum}}, "max" => {{maximum}}{{#exclusiveMinimum}}, "exclude_min" => true{{/exclusiveMinimum}}{{#exclusiveMaximum}}, "exclude_max" => true{{/exclusiveMaximum}}])]
{{/maximum}}{{/minimum
}}{{^minimum}}{{#maximum
}} #[DTA\Validator("Range", ["max" => {{maximum}}{{#exclusiveMaximum}}, "exclude_max" => true{{/exclusiveMaximum}}])]
{{/maximum}}{{/minimum
}}{{#minimum}}{{^maximum
}} #[DTA\Validator("Range", ["min" => {{minimum}}{{#exclusiveMinimum}}, "exclude_min" => true{{/exclusiveMinimum}}])]
{{/maximum}}{{/minimum
}}{{#minimum
}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}])]
{{/minimum
}}{{#maximum
}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}])]
{{/maximum
}}{{#pattern
}} #[DTA\Validator("Match", ["pattern" => "{{{pattern}}}"])]
}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"])]
{{/pattern
}}{{/hasValidation}}

View File

@@ -21,7 +21,7 @@
{{/isDate
}}{{#isDateTime
}} #[DTA\Strategy("DateTime", subset: "{{internal.parameterLocation}}")]
#[DTA\Validator("DateTime", subset: "{{internal.parameterLocation}}")]
#[DTA\Validator("Date", ["format" => \DateTime::RFC3339], subset: "{{internal.parameterLocation}}")]
{{/isDateTime
}}{{^isPrimitiveType
}}{{^isDate}}{{^isDateTime
@@ -31,24 +31,21 @@
}}{{/isContainer
}}{{#hasValidation
}}{{#minLength}}{{#maxLength
}} #[DTA\Validator("Length", ["min" => {{minLength}}, "max" => {{maxLength}}], subset: "{{internal.parameterLocation}}")]
}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}], subset: "{{internal.parameterLocation}}")]
{{/maxLength}}{{/minLength
}}{{^minLength}}{{#maxLength
}} #[DTA\Validator("Length", ["max" => {{maxLength}}], subset: "{{internal.parameterLocation}}")]
}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}], subset: "{{internal.parameterLocation}}")]
{{/maxLength}}{{/minLength
}}{{#minLength}}{{^maxLength
}} #[DTA\Validator("Length", ["min" => {{minLength}}], subset: "{{internal.parameterLocation}}")]
}} #[DTA\Validator("StringLength", ["min" => {{minLength}}], subset: "{{internal.parameterLocation}}")]
{{/maxLength}}{{/minLength
}}{{#minimum}}{{#maximum
}} #[DTA\Validator("Range", ["min" => {{minimum}}, "max" => {{maximum}}{{#exclusiveMinimum}}, "exclude_min" => true{{/exclusiveMinimum}}{{#exclusiveMaximum}}, "exclude_max" => true{{/exclusiveMaximum}}], subset: "{{internal.parameterLocation}}")]
{{/maximum}}{{/minimum
}}{{^minimum}}{{#maximum
}} #[DTA\Validator("Range", ["max" => {{maximum}}{{#exclusiveMaximum}}, "exclude_max" => true{{/exclusiveMaximum}}], subset: "{{internal.parameterLocation}}")]
{{/maximum}}{{/minimum
}}{{#minimum}}{{^maximum
}} #[DTA\Validator("Range", ["min" => {{minimum}}{{#exclusiveMinimum}}, "exclude_min" => true{{/exclusiveMinimum}}], subset: "{{internal.parameterLocation}}")]
{{/maximum}}{{/minimum
}}{{#minimum
}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}], subset: "{{internal.parameterLocation}}")]
{{/minimum
}}{{#maximum
}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}], subset: "{{internal.parameterLocation}}")]
{{/maximum
}}{{#pattern
}} #[DTA\Validator("Match", ["pattern" => "{{{pattern}}}"], subset: "{{internal.parameterLocation}}")]
}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"], subset: "{{internal.parameterLocation}}")]
{{/pattern
}}{{/hasValidation}}

View File

@@ -44,17 +44,7 @@ class ApiClient extends OAGAC\AbstractApiClient
$request = $this->addCookies($request, $parameters);
{{/cookieParams.0}}
{{#bodyParam}}
{{#isDate}}
$request = $this->addBody($request, $requestMediaType, $requestContent, ($this->contentStrategies)('Date', []));
{{/isDate}}
{{#isDateTime}}
$request = $this->addBody($request, $requestMediaType, $requestContent, ($this->contentStrategies)('DateTime', []));
{{/isDateTime}}
{{^isDate}}
{{^isDateTime}}
$request = $this->addBody($request, $requestMediaType, $requestContent);
{{/isDateTime}}
{{/isDate}}
{{/bodyParam}}
{{#hasProduces}}
$request = $this->addAcceptHeader($request, $responseMediaType);
@@ -78,8 +68,6 @@ class ApiClient extends OAGAC\AbstractApiClient
{
$response = $this->{{operationId}}Raw({{>api_arg_call}});
$responseContent = null;
$contentStrategy = null;
$contentValidator = null;
switch ($response->getStatusCode())
{
{{#responses}}
@@ -87,35 +75,25 @@ class ApiClient extends OAGAC\AbstractApiClient
{{#message}}
/* {{&message}} */
{{/message}}
{{#isArray}}
$responseContent = new {{dataType}}();
{{/isArray}}
{{#isMap}}
$responseContent = new {{dataType}}();
{{/isMap}}
{{#isDate}}
$contentStrategy = ($this->contentStrategies)('Date', []);
$contentValidator = ($this->contentValidators)('Date', []);
{{/isDate}}
{{#isDateTime}}
$contentStrategy = ($this->contentStrategies)('DateTime', []);
$contentValidator = ($this->contentValidators)('DateTime', []);
{{/isDateTime}}
{{^isDate}}
{{^isDateTime}}
{{^isArray}}
{{^isMap}}
{{#isModel}}
$responseContent = new {{dataType}}();
{{/isModel}}
{{^isModel}}
{{#isArray}}
$responseContent = new {{dataType}}();
{{/isArray}}
{{/isModel}}
{{^isModel}}
{{^isArray}}
{{#isMap}}
$responseContent = new {{dataType}}();
{{/isMap}}
{{/isArray}}
{{/isDateTime}}
{{/isDate}}
{{/isModel}}
break;
{{/responses}}
}
$this->parseBody($response, $responseContent, $contentStrategy, $contentValidator);
$this->parseBody($response, $responseContent);
return [$responseContent, $response->getHeaders(), $response->getStatusCode(), $response->getReasonPhrase()];
}

View File

@@ -3,20 +3,18 @@ declare(strict_types=1);
namespace {{invokerPackage}};
use Articus\PluginManager as PM;
use Articus\DataTransfer as DT;
use Interop\Container\ContainerInterface;
use OpenAPIGenerator\APIClient as OAGAC;
use Psr\Container\ContainerInterface;
class ApiClientFactory implements PM\ServiceFactoryInterface
class ApiClientFactory extends DT\ConfigAwareFactory
{
use PM\ConfigAwareFactoryTrait;
public function __construct(string $configKey = ApiClient::class)
{
$this->configKey = $configKey;
parent::__construct($configKey);
}
public function __invoke(ContainerInterface $container, $requestedName, array $options = null): ApiClient
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = new OAGAC\ApiClientOptions(\array_merge($this->getServiceConfig($container), $options ?? []));
return new ApiClient(
@@ -26,9 +24,7 @@ class ApiClientFactory implements PM\ServiceFactoryInterface
$container->get($config->httpClientServiceName),
$container->get($config->securityProviderFactoryServiceName),
$container->get($config->bodyCoderFactoryServiceName),
$container->get($config->bodyCoderFactoryServiceName),
$container->get($config->contentStrategyFactoryServiceName),
$container->get($config->contentValidatorFactoryServiceName)
$container->get($config->bodyCoderFactoryServiceName)
);
}
}

View File

@@ -5,8 +5,8 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project.
## Overview
This lightweight extensible client library is [PSR-7](https://www.php-fig.org/psr/psr-7), [PSR-11](https://www.php-fig.org/psr/psr-11), [PSR-17](https://www.php-fig.org/psr/psr-17) and [PSR-18](https://www.php-fig.org/psr/psr-18) complaint and relies on:
- PHP: >=7.4
- [Data Transfer](https://github.com/Articus/DataTransfer): >=0.6
- PHP: >=7.3
- [Data Transfer](https://github.com/Articus/DataTransfer): >=0.5
## How to use
@@ -21,7 +21,7 @@ Then check content types for API requests you intend to send and API responses y
After that review security requirements for API operations you intend to use. For each unique security scheme you will need an implementation of [OpenAPIGenerator\APIClient\SecurityProviderInterface](https://github.com/Articus/OpenAPIGeneratorAPIClient-PHP/blob/master/src/OpenAPIGenerator/APIClient/SecurityProviderInterface.php). Currently, only [HTTP Bearer authentication](https://github.com/Articus/OpenAPIGeneratorAPIClient-PHP/blob/master/src/OpenAPIGenerator/APIClient/SecurityProvider/HttpBearer.php) is supported out-of-the-box.
The last step is to configure and wire all services together. It is highly advisable to use [PSR-11 container](https://packagist.org/packages/psr/container) for that. If you have not selected one for your project yet, https://packagist.org/providers/psr/container-implementation may help to find some suitable options. Here is a sample wiring configuration for `"laminas/laminas-servicemanager"`, `"nyholm/psr7"` and `"symfony/http-client"` (consult generated `composer.json` for the exact versions of used packages):
The last step is to configure and wire all services together. It is highly advisable to use [PSR-11 container](https://packagist.org/packages/psr/container) for that. If you have not selected one for your project yet, https://packagist.org/providers/psr/container-implementation may help to find some suitable options. Here is a sample wiring configuration for `"laminas/laminas-servicemanager"`, `"laminas/laminas-diactoros"` and `"symfony/http-client"` (consult generated `composer.json` for the exact versions of used packages):
```PHP
<?php
@@ -31,24 +31,21 @@ require_once __DIR__ . '/vendor/autoload.php';
$dependencies = [
'invokables' => [
Psr\Http\Message\RequestFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\ResponseFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\StreamFactoryInterface::class => Nyholm\Psr7\Factory\Psr17Factory::class,
Psr\Http\Message\RequestFactoryInterface::class => Laminas\Diactoros\RequestFactory::class,
Psr\Http\Message\ResponseFactoryInterface::class => Laminas\Diactoros\ResponseFactory::class,
Psr\Http\Message\StreamFactoryInterface::class => Laminas\Diactoros\StreamFactory::class,
],
'factories' => [
{{invokerPackage}}\ApiClient::class => {{invokerPackage}}\ApiClientFactory::class,
Articus\DataTransfer\Service::class => Articus\DataTransfer\Factory::class,
Articus\DataTransfer\MetadataProvider\Annotation::class => Articus\DataTransfer\MetadataProvider\Factory\Annotation::class,
Articus\DataTransfer\Options::DEFAULT_STRATEGY_PLUGIN_MANAGER => [Articus\PluginManager\Factory\Chain::class, 'app_dt_strategy_manager_chain'],
'oas_dt_strategy_manager' => OpenAPIGenerator\Common\Strategy\Factory\PluginManager::class,
'app_dt_strategy_manager' => Articus\DataTransfer\Strategy\Factory\SimplePluginManager::class,
Articus\DataTransfer\Options::DEFAULT_VALIDATOR_PLUGIN_MANAGER => [Articus\PluginManager\Factory\Chain::class, 'app_dt_validator_manager_chain'],
'oas_dt_validator_manager' => OpenAPIGenerator\Common\Validator\Factory\PluginManager::class,
'app_dt_validator_manager' => Articus\DataTransfer\Validator\Factory\SimplePluginManager::class,
Articus\DataTransfer\Strategy\PluginManager::class => Articus\DataTransfer\Strategy\Factory\PluginManager::class,
Articus\DataTransfer\Validator\PluginManager::class => Articus\DataTransfer\Validator\Factory\PluginManager::class,
Laminas\Validator\ValidatorPluginManager::class => Laminas\Validator\ValidatorPluginManagerFactory::class,
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_BODY_CODER_PLUGIN_MANAGER => OpenAPIGenerator\APIClient\BodyCoder\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER => OpenAPIGenerator\APIClient\SecurityProvider\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class => OpenAPIGenerator\APIClient\SecurityProvider\Factory\PluginManager::class,
OpenAPIGenerator\APIClient\BodyCoder\PluginManager::class => OpenAPIGenerator\APIClient\BodyCoder\Factory\PluginManager::class,
Psr\Http\Client\ClientInterface::class => function (Psr\Container\ContainerInterface $container)
{
@@ -67,17 +64,34 @@ $dependencies = [
$config = [
'dependencies' => $dependencies,
//Configure DataTransfer library: add pack of extra strategies and pack of extra validators
'app_dt_strategy_manager_chain' => [
'managers' => [
'oas_dt_strategy_manager',
'app_dt_strategy_manager',
//Configure DataTransfer library
Articus\DataTransfer\Strategy\PluginManager::class => [
'invokables' => [
'QueryStringScalar' => OpenAPIGenerator\Common\Strategy\QueryStringScalar::class,
'QueryStringScalarArray' => OpenAPIGenerator\Common\Strategy\QueryStringScalarArray::class,
],
'factories' => [
'Date' => OpenAPIGenerator\Common\Strategy\Factory\ImmutableDate::class,
'DateTime' => OpenAPIGenerator\Common\Strategy\Factory\ImmutableDateTime::class,
'ObjectList' => OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList::class,
'ObjectMap' => OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap::class,
'ScalarList' => OpenAPIGenerator\Common\Strategy\Factory\ScalarList::class,
'ScalarMap' => OpenAPIGenerator\Common\Strategy\Factory\ScalarMap::class,
]
],
Articus\DataTransfer\Validator\PluginManager::class => [
'invokables' => [
'Scalar' => OpenAPIGenerator\Common\Validator\Scalar::class,
'QueryStringScalar' => OpenAPIGenerator\Common\Validator\QueryStringScalar::class,
'QueryStringScalarArray' => OpenAPIGenerator\Common\Validator\QueryStringScalarArray::class,
],
'abstract_factories' => [
Articus\DataTransfer\Validator\Factory\Laminas::class,
],
],
'app_dt_validator_manager_chain' => [
'managers' => [
'oas_dt_validator_manager',
'app_dt_validator_manager',
'validators' => [
'invokables' => [
'Count' => Laminas\Validator\IsCountable::class,
],
],
@@ -87,19 +101,19 @@ $config = [
],
//Register body coders for used content types here
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_BODY_CODER_PLUGIN_MANAGER => [
OpenAPIGenerator\APIClient\BodyCoder\PluginManager::class => [
'factories' => [
//'another/mime-type' => AnotherMimeTypeBodyCoder::class
],
],
//Register security providers for used security schemes here
OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER => [
OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class => [
'factories' => [
//'another-security-scheme' => AnotherSecuritySchemeProvider::class,
],
'aliases' => [
//'custom-name-for-http-bearer' => OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class,
//'custom-name-for-htt-bearer' => OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class,
],
],
];
@@ -112,10 +126,10 @@ $client = $container->get({{invokerPackage}}\ApiClient::class);
//... and now you can use client methods to call API operations :)
//And one more sample: how to set token for HTTP Bearer authentication
/** @var Articus\PluginManager\PluginManagerInterface $securityProviders */
$securityProviders = $container->get(OpenAPIGenerator\APIClient\ApiClientOptions::DEFAULT_SECURITY_PROVIDER_PLUGIN_MANAGER);
/** @var OpenAPIGenerator\APIClient\SecurityProvider\PluginManager $securityProviders */
$securityProviders = $container->get(OpenAPIGenerator\APIClient\SecurityProvider\PluginManager::class);
/** @var OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer $httpBearer */
$httpBearer = $securityProviders(OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class, []);
$httpBearer = $securityProviders->get(OpenAPIGenerator\APIClient\SecurityProvider\HttpBearer::class);
$httpBearer->setToken('some-token');
```

View File

@@ -13,7 +13,7 @@
* @param {{dataType}} $requestContent
{{/bodyParam}}
{{#hasAuthMethods}}
* @param iterable<string, string[]> $security
* @param iterable|string[][] $security
{{/hasAuthMethods}}
{{#hasConsumes}}
* @param string $requestMediaType

View File

@@ -18,13 +18,14 @@
"version": "{{artifactVersion}}",
"type": "library",
"require": {
"php": "^7.4 || ^8.0",
"articus/data-transfer": "^0.6",
"articus/openapi-generator-common": "^0.3",
"articus/openapi-generator-apiclient": "^0.2",
"doctrine/annotations": "^2.0",
"php": "^7.3 || ^8.0",
"articus/data-transfer": "^0.5",
"articus/openapi-generator-common": "^0.2",
"articus/openapi-generator-apiclient": "^0.1",
"doctrine/annotations": "^1.10",
"psr/simple-cache": "^1.0",
"laminas/laminas-stdlib": "^3.13"
"laminas/laminas-stdlib": "^3.2",
"laminas/laminas-validator": "^2.13"
},
"autoload": {
"psr-4": {
@@ -32,8 +33,8 @@
}
},
"require-dev": {
"laminas/laminas-servicemanager": "^3.17",
"nyholm/psr7": "^1.8",
"symfony/http-client": "^5.4"
"laminas/laminas-servicemanager": "^3.6",
"laminas/laminas-diactoros": "^2.6",
"symfony/http-client": "^5.3"
}
}

View File

@@ -1,19 +1,8 @@
/**
{{#vars
}}{{#isArray
}}{{#isPrimitiveType
}} * @DTA\Strategy(name="ScalarList", options={"type":{{>list_item_type}}})
{{/isPrimitiveType
}}{{#items.isDate
}} * @DTA\Strategy(name="DateList")
{{/items.isDate
}}{{#items.isDateTime
}} * @DTA\Strategy(name="DateTimeList")
{{/items.isDateTime
}}{{^isPrimitiveType}}{{^items.isDate}}{{^items.isDateTime
}} * @DTA\Strategy(name="ObjectList", options={"type":{{>list_item_type}}})
{{/items.isDateTime}}{{/items.isDate}}{{/isPrimitiveType
}}{{#minItems}}{{^maxItems
}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", options={"type":{{>list_item_type}}})
{{#minItems}}{{^maxItems
}} * @DTA\Validator(name="Count", options={"min":{{minItems}}}, blocker=true)
{{/maxItems}}{{/minItems
}}{{^minItems}}{{#maxItems
@@ -26,31 +15,20 @@
{{#isPrimitiveType
}} * {"name":"Scalar", "options":{"type":{{>list_item_type}}}}
{{/isPrimitiveType
}}{{#items.isDate
}}{{#isDate
}} * {"name":"Date"}
{{/items.isDate
}}{{#items.isDateTime
}} * {"name":"DateTime"}
{{/items.isDateTime
}}{{^isPrimitiveType}}{{^items.isDate}}{{^items.isDateTime
{{/isDate
}}{{#isDateTime
}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}}
{{/isDateTime
}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime
}} * {"name":"TypeCompliant", "options":{"type":{{>list_item_type}}}}
{{/items.isDateTime}}{{/items.isDate}}{{/isPrimitiveType
{{/isDateTime}}{{/isDate}}{{/isPrimitiveType
}} * }})
{{/isArray
}}{{#isMap
}}{{#isPrimitiveType
}} * @DTA\Strategy(name="ScalarMap", options={"type":{{>map_item_type}}})
{{/isPrimitiveType
}}{{#additionalProperties.isDate
}} * @DTA\Strategy(name="DateMap")
{{/additionalProperties.isDate
}}{{#additionalProperties.isDateTime
}} * @DTA\Strategy(name="DateTimeMap")
{{/additionalProperties.isDateTime
}}{{^isPrimitiveType}}{{^additionalProperties.isDate}}{{^additionalProperties.isDateTime
}} * @DTA\Strategy(name="ObjectMap", options={"type":{{>map_item_type}}})
{{/additionalProperties.isDateTime}}{{/additionalProperties.isDate}}{{/isPrimitiveType
}}{{#minProperties}}{{^maxProperties
}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", options={"type":{{>map_item_type}}})
{{#minProperties}}{{^maxProperties
}} * @DTA\Validator(name="Count", options={"min":{{minProperties}}}, blocker=true)
{{/maxProperties}}{{/minProperties
}}{{^minProperties}}{{#maxProperties
@@ -63,15 +41,15 @@
{{#isPrimitiveType
}} * {"name":"Scalar", "options":{"type":{{>map_item_type}}}}
{{/isPrimitiveType
}}{{#additionalProperties.isDate
}}{{#isDate
}} * {"name":"Date"}
{{/additionalProperties.isDate
}}{{#additionalProperties.isDateTime
}} * {"name":"DateTime"}
{{/additionalProperties.isDateTime
}}{{^isPrimitiveType}}{{^additionalProperties.isDate}}{{^additionalProperties.isDateTime
{{/isDate
}}{{#isDateTime
}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}}
{{/isDateTime
}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime
}} * {"name":"TypeCompliant", "options":{"type":{{>map_item_type}}}}
{{/additionalProperties.isDateTime}}{{/additionalProperties.isDate}}{{/isPrimitiveType
{{/isDateTime}}{{/isDate}}{{/isPrimitiveType
}} * }})
{{/isMap
}}{{/vars

View File

@@ -12,7 +12,7 @@
{{/isDate
}}{{#isDateTime
}} * @DTA\Strategy(name="DateTime")
* @DTA\Validator(name="DateTime")
* @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339})
{{/isDateTime
}}{{^isPrimitiveType
}}{{^isDate
@@ -25,24 +25,21 @@
}}{{/isContainer
}}{{#hasValidation
}}{{#minLength}}{{#maxLength
}} * @DTA\Validator(name="Length", options={"min":{{minLength}}, "max":{{maxLength}}})
}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}})
{{/maxLength}}{{/minLength
}}{{^minLength}}{{#maxLength
}} * @DTA\Validator(name="Length", options={"max":{{maxLength}}})
}} * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}})
{{/maxLength}}{{/minLength
}}{{#minLength}}{{^maxLength
}} * @DTA\Validator(name="Length", options={"min":{{minLength}}})
}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}})
{{/maxLength}}{{/minLength
}}{{#minimum}}{{#maximum
}} * @DTA\Validator(name="Range", options={"min":{{minimum}}, "max":{{maximum}}{{#exclusiveMinimum}}, "exclude_min":true{{/exclusiveMinimum}}{{#exclusiveMaximum}}, "exclude_max":true{{/exclusiveMaximum}}})
{{/maximum}}{{/minimum
}}{{^minimum}}{{#maximum
}} * @DTA\Validator(name="Range", options={"max":{{maximum}}{{#exclusiveMaximum}}, "exclude_max":true{{/exclusiveMaximum}}})
{{/maximum}}{{/minimum
}}{{#minimum}}{{^maximum
}} * @DTA\Validator(name="Range", options={"min":{{minimum}}{{#exclusiveMinimum}}, "exclude_min":true{{/exclusiveMinimum}}})
{{/maximum}}{{/minimum
}}{{#minimum
}} * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}})
{{/minimum
}}{{#maximum
}} * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}})
{{/maximum
}}{{#pattern
}} * @DTA\Validator(name="Match", options={"pattern":"{{{pattern}}}"})
}} * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"})
{{/pattern
}}{{/hasValidation}}

View File

@@ -1,9 +1,9 @@
/**
{{#description
}}/**
* {{description}}
*/
}} * {{description}}
{{/description
}}class {{classname}}
}} */
class {{classname}}
{
{{#vars
}} /**
@@ -16,8 +16,9 @@
}}{{^internal.fromParameters}}{{>model_normal_var}}{{/internal.fromParameters
}}{{/vendorExtensions
}}{{^vendorExtensions}}{{>model_normal_var}}{{/vendorExtensions
}} */
public ?{{dataType}} ${{name}} = null;
}} * @var {{dataType}}|null
*/
public ${{name}};
{{/vars
}}}

View File

@@ -21,7 +21,7 @@
{{/isDate
}}{{#isDateTime
}} * @DTA\Strategy(subset="{{internal.parameterLocation}}", name="DateTime")
* @DTA\Validator(subset="{{internal.parameterLocation}}", name="DateTime")
* @DTA\Validator(subset="{{internal.parameterLocation}}", name="Date", options={"format": \DateTime::RFC3339})
{{/isDateTime
}}{{^isPrimitiveType
}}{{^isDate}}{{^isDateTime
@@ -31,24 +31,21 @@
}}{{/isContainer
}}{{#hasValidation
}}{{#minLength}}{{#maxLength
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Length", options={"min":{{minLength}}, "max":{{maxLength}}})
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}})
{{/maxLength}}{{/minLength
}}{{^minLength}}{{#maxLength
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Length", options={"max":{{maxLength}}})
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="StringLength", options={"max":{{maxLength}}})
{{/maxLength}}{{/minLength
}}{{#minLength}}{{^maxLength
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Length", options={"min":{{minLength}}})
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="StringLength", options={"min":{{minLength}}})
{{/maxLength}}{{/minLength
}}{{#minimum}}{{#maximum
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Range", options={"min":{{minimum}}, "max":{{maximum}}{{#exclusiveMinimum}}, "exclude_min":true{{/exclusiveMinimum}}{{#exclusiveMaximum}}, "exclude_max":true{{/exclusiveMaximum}}})
{{/maximum}}{{/minimum
}}{{^minimum}}{{#maximum
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Range", options={"max":{{maximum}}{{#exclusiveMaximum}}, "exclude_max":true{{/exclusiveMaximum}}})
{{/maximum}}{{/minimum
}}{{#minimum}}{{^maximum
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Range", options={"min":{{minimum}}{{#exclusiveMinimum}}, "exclude_min":true{{/exclusiveMinimum}}})
{{/maximum}}{{/minimum
}}{{#minimum
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}})
{{/minimum
}}{{#maximum
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}})
{{/maximum
}}{{#pattern
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Match", options={"pattern":"{{{pattern}}}"})
}} * @DTA\Validator(subset="{{internal.parameterLocation}}", name="Regex", options={"pattern":"{{{pattern}}}"})
{{/pattern
}}{{/hasValidation}}

View File

@@ -51,7 +51,7 @@ function Invoke-{{{apiNamePrefix}}}ApiClient {
}
# accept, content-type headers
$Accept = SelectHeaders -Headers $Accepts -Multiple -JsonFirst
$Accept = SelectHeaders -Headers $Accepts
if ($Accept) {
$HeaderParameters['Accept'] = $Accept
}
@@ -115,6 +115,8 @@ function Invoke-{{{apiNamePrefix}}}ApiClient {
}
}
if ($Body -or $IsBodyNullable) {
$RequestBody = $Body
if ([string]::IsNullOrEmpty($RequestBody) -and $IsBodyNullable -eq $true) {
@@ -192,46 +194,24 @@ function Invoke-{{{apiNamePrefix}}}ApiClient {
}
}
# Filter MIME types for Accept:/Content-Type: headers
# Select JSON MIME if present, otherwise choose the first one if available
function SelectHeaders {
Param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[String[]]$Headers,
[Parameter(Mandatory=$false)]
[switch]$Multiple,
[Parameter(Mandatory=$false)]
[switch]$JsonFirst
[String[]]$Headers
)
# if no MIME type is provided return null
if (!($Headers) -or $Headers.Count -eq 0) {
return $null
foreach ($Header in $Headers) {
if (IsJsonMIME -MIME $Header) {
return $Header
}
}
if ($Multiple) {
# return multiple MIME types (for Accept: header)
if ($JsonFirst) {
# sort input to return JSON MIME types first
$mimeHeaders = @()
$otherHeaders = @()
foreach ($Header in $Headers) {
if (IsJsonMIME -MIME $Header) {
$mimeHeaders += $Header
} else {
$otherHeaders += $Header
}
}
$Headers = $($mimeHeaders; $otherHeaders)
}
return [string]::Join(', ', $Headers) # join multiple types if they are provided
if (!($Headers) -or $Headers.Count -eq 0) {
return $null
} else {
foreach ($Header in $Headers) {
if (IsJsonMIME -MIME $Header) {
return $Header # return the first type matching a JSON MIME
}
}
return $Headers[0] # else return the first one
return $Headers[0] # return the first one
}
}

View File

@@ -1 +1 @@
{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}{{#isPathParam}}...{{/isPathParam}}{{^isPathParam}}None{{/isPathParam}}{{/defaultValue}}, description="{{description}}"{{#isQueryParam}}, alias="{{baseName}}"{{/isQueryParam}}{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}})
{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}None{{/defaultValue}}, description="{{description}}"{{#isQueryParam}}, alias="{{baseName}}"{{/isQueryParam}}{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}})

View File

@@ -4,7 +4,6 @@
import datetime
from dateutil.parser import parse
from enum import Enum
import json
import mimetypes
import os
@@ -438,8 +437,6 @@ class ApiClient:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datetime(data)
elif issubclass(klass, Enum):
return self.__deserialize_enum(data, klass)
else:
return self.__deserialize_model(data, klass)
@@ -746,24 +743,6 @@ class ApiClient:
)
)
def __deserialize_enum(self, data, klass):
"""Deserializes primitive type to enum.
:param data: primitive type.
:param klass: class literal.
:return: enum value.
"""
try:
return klass(data)
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as `{1}`"
.format(data, klass)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.

View File

@@ -64,11 +64,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/required}}
{{#isArray}}
for i in value:
if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]):
if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
{{/isArray}}
{{^isArray}}
if value not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]):
if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
{{/isArray}}
return value

View File

@@ -11,8 +11,7 @@ import scala.reflect.ClassTag
object JsonSupport extends SttpJson4sApi {
def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#isEnum}} :+
new EnumNameSerializer({{classname}}){{/isEnum}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+
new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}}
new EnumNameSerializer({{classname}}){{/isEnum}}{{/model}}{{/models}}
private class EnumNameSerializer[E <: Enumeration: ClassTag](enumeration: E) extends Serializer[E#Value] {
import JsonDSL._

View File

@@ -1,69 +1,57 @@
# TypeScript-Aurelia
This generator creates TypeScript/JavaScript client that is injectable by [Aurelia](http://aurelia.io/).
The generated Node module can be used in the following environments:
The generated Node module can be used in the following environments:
Environment
- Node.js
- Webpack
- Browserify
* Node.js
* Webpack
* Browserify
Language level
- ES5 - you must have a Promises/A+ library installed
- ES6
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
- CommonJS
- ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
### Building
### Building ####
To build and compile the typescript sources to javascript use:
```
npm install
npm run build
```
#### NPM
#### NPM ####
You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It may be useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project.
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project.
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
```
The CommonJS syntax is as follows:
```
import localName = require('npmName');
```
#### Direct copy/symlink
#### Direct copy/symlink ####
You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows:
With ES6 module syntax, the following syntaxes are supported:
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
The CommonJS syntax is as follows:
```
import localName = require('./symlinkDir')';
```

View File

@@ -15,7 +15,7 @@ Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Building
@@ -27,7 +27,7 @@ npm run build
### Publishing
First build the package then run `npm publish`
First build the package then run ```npm publish```
### Consuming
@@ -43,4 +43,3 @@ _unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```

View File

@@ -5,7 +5,7 @@
*/
export interface {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{
{{#additionalPropertiesType}}
[key: string]: {{{additionalPropertiesType}}}{{#additionalPropertiesIsAnyType}}{{#hasVars}} | any{{/hasVars}}{{/additionalPropertiesIsAnyType}};
[key: string]: {{{additionalPropertiesType}}}{{^additionalPropertiesIsAnyType}}{{#hasVars}} | any{{/hasVars}}{{/additionalPropertiesIsAnyType}};
{{/additionalPropertiesType}}
{{#vars}}

View File

@@ -15,7 +15,7 @@ Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Building
@@ -27,7 +27,7 @@ npm run build
### Publishing
First build the package then run `npm publish`
First build the package then run ```npm publish```
### Consuming
@@ -43,4 +43,3 @@ _unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```

View File

@@ -191,13 +191,13 @@ export class {{classname}} extends runtime.BaseAPI {
{{#isApiKey}}
{{#isKeyInHeader}}
if (this.configuration && this.configuration.apiKey) {
headerParameters["{{keyParamName}}"] = await this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
headerParameters["{{keyParamName}}"] = this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (this.configuration && this.configuration.apiKey) {
queryParameters["{{keyParamName}}"] = await this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
queryParameters["{{keyParamName}}"] = this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
}
{{/isKeyInQuery}}

View File

@@ -11,7 +11,7 @@ export interface ConfigurationParameters {
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
username?: string; // parameter for basic security
password?: string; // parameter for basic security
apiKey?: string | Promise<string> | ((name: string) => string | Promise<string>); // parameter for apiKey security
apiKey?: string | ((name: string) => string); // parameter for apiKey security
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
headers?: HTTPHeaders; //header params we want to use on every request
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
@@ -48,7 +48,7 @@ export class Configuration {
return this.configuration.password;
}
get apiKey(): ((name: string) => string | Promise<string>) | undefined {
get apiKey(): ((name: string) => string) | undefined {
const apiKey = this.configuration.apiKey;
if (apiKey) {
return typeof apiKey === 'function' ? apiKey : () => apiKey;

View File

@@ -15,7 +15,7 @@ Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html))
### Building
@@ -27,7 +27,7 @@ npm run build
### Publishing
First build the package then run `npm publish`
First build the package then run ```npm publish```
### Consuming
@@ -43,4 +43,3 @@ _unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```

View File

@@ -121,7 +121,7 @@ export class {{classname}} {
// authentication ({{name}}) required
{{#isApiKey}}
{{#isKeyInHeader}}
if (this.configuration.apiKeys?.["{{keyParamName}}"]) {
if (this.configuration.apiKeys["{{keyParamName}}"]) {
headers['{{keyParamName}}'] = this.configuration.apiKeys["{{keyParamName}}"];
}
@@ -130,7 +130,7 @@ export class {{classname}} {
{{^hasQueryParams}}
let queryParameters = new URLSearchParams();
{{/hasQueryParams}}
if (this.configuration.apiKeys?.["{{keyParamName}}"]) {
if (this.configuration.apiKeys["{{keyParamName}}"]) {
queryParameters.append('{{keyParamName}}', this.configuration.apiKeys["{{keyParamName}}"]);
}
@@ -142,13 +142,6 @@ export class {{classname}} {
}
{{/isBasicBasic}}
{{#isBasicBearer}}
if (typeof this.configuration.accessToken === 'function') {
headers['Authorization'] = `Bearer ${this.configuration.accessToken()}`;
} else if (this.configuration.accessToken) {
headers['Authorization'] = `Bearer ${this.configuration.accessToken}`;
}
{{/isBasicBearer}}
{{#isOAuth}}
if (this.configuration.accessToken) {
const accessToken = typeof this.configuration.accessToken === 'function'

View File

@@ -3,7 +3,7 @@
This generator creates TypeScript/JavaScript client that utilizes [redux-query](https://amplitude.github.io/redux-query/).
The generated Node module does not depend on ReactJS specifically.
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Building
@@ -15,7 +15,7 @@ npm run build
### Publishing
First build the package then run `npm publish`
First build the package then run ```npm publish```
### Consuming
@@ -31,4 +31,3 @@ _unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```

View File

@@ -15,7 +15,7 @@ Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Building

View File

@@ -136,15 +136,6 @@ public class OpenAPINormalizerTest {
assertTrue(schema3.getEnum().size() > 0);
}
@Test
public void isNullTypeSchemaTest() {
OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/simplifyOneOfAnyOf_test.yaml");
Map<String, String> options = new HashMap<>();
OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, options);
Schema schema = openAPI.getComponents().getSchemas().get("AnyOfStringArrayOfString");
assertFalse(openAPINormalizer.isNullTypeSchema(schema));
}
@Test
public void testOpenAPINormalizerSimplifyOneOfAnyOf() {
// to test the rule SIMPLIFY_ONEOF_ANYOF
@@ -165,9 +156,6 @@ public class OpenAPINormalizerTest {
Schema schema7 = openAPI.getComponents().getSchemas().get("Parent");
assertEquals(((Schema) schema7.getProperties().get("number")).getAnyOf().size(), 1);
Schema schema9 = openAPI.getComponents().getSchemas().get("AnyOfStringArrayOfString");
assertEquals(schema9.getAnyOf().size(), 2);
Map<String, String> options = new HashMap<>();
options.put("SIMPLIFY_ONEOF_ANYOF", "true");
OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, options);
@@ -189,9 +177,6 @@ public class OpenAPINormalizerTest {
Schema schema8 = openAPI.getComponents().getSchemas().get("Parent");
assertEquals(((Schema) schema8.getProperties().get("number")).get$ref(), "#/components/schemas/Number");
Schema schema10 = openAPI.getComponents().getSchemas().get("AnyOfStringArrayOfString");
assertEquals(schema10.getAnyOf().size(), 2);
}
@Test
@@ -400,7 +385,7 @@ public class OpenAPINormalizerTest {
Schema pet = openAPI.getComponents().getSchemas().get("Pet");
// verify schema for property id
Schema petSchema = (Schema) pet.getProperties().get("id");
Schema petSchema = (Schema)pet.getProperties().get("id");
// both type and types are defined
assertNotNull(petSchema.getType());
assertNotNull(petSchema.getTypes());
@@ -429,24 +414,4 @@ public class OpenAPINormalizerTest {
assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getType());
assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getTypes());
}
@Test
public void testRemoveXInternal() {
OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml");
Schema s = openAPI.getComponents().getSchemas().get("Dummy");
assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getExtensions(), null);
assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getExtensions().get("x-internal"), true);
assertEquals(s.getExtensions().get("x-internal"), true);
Map<String, String> options = new HashMap<>();
options.put("REMOVE_X_INTERNAL", "true");
OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, options);
openAPINormalizer.normalize();
Schema s2 = openAPI.getComponents().getSchemas().get("Dummy");
assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getExtensions(), null);
assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getExtensions().get("x-internal"), null);
assertEquals(s2.getExtensions().get("x-internal"), null);
}
}
}

View File

@@ -17,18 +17,14 @@
package org.openapitools.codegen.java;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.parser.core.models.ParseOptions;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.AbstractJavaCodegen;
import org.openapitools.codegen.utils.ModelUtils;
@@ -877,26 +873,6 @@ public class AbstractJavaCodegenTest {
Assert.assertTrue(cm.imports.contains("UUID"));
}
@Test
public void arrayParameterDefaultValueDoesNotNeedBraces() throws Exception {
ParseOptions parseOptions = new ParseOptions();
parseOptions.setResolve(true);
final OpenAPI openAPI = new OpenAPIParser()
.readLocation("src/test/resources/3_0/issue_16223.yaml", null, parseOptions)
.getOpenAPI();
final P_AbstractJavaCodegen codegen = new P_AbstractJavaCodegen();
codegen.setOpenAPI(openAPI);
Map<String, Schema> schemas = openAPI.getPaths().get("/test").getGet().getParameters().stream()
.collect(Collectors.toMap(
Parameter::getName,
p -> ModelUtils.getReferencedSchema(openAPI, p.getSchema())));
Assert.assertEquals(codegen.toDefaultParameterValue(schemas.get("fileEnumWithDefault")), "A,B");
Assert.assertEquals(codegen.toDefaultParameterValue(schemas.get("fileEnumWithDefaultEmpty")), "");
Assert.assertEquals(codegen.toDefaultParameterValue(schemas.get("inlineEnumWithDefault")), "A,B");
Assert.assertEquals(codegen.toDefaultParameterValue(schemas.get("inlineEnumWithDefaultEmpty")), "");
}
private static Schema<?> createObjectSchemaWithMinItems() {
return new ObjectSchema()
.addProperties("id", new IntegerSchema().format("int32"))

View File

@@ -2643,129 +2643,6 @@ public class JavaClientCodegenTest {
TestUtils.assertFileContains(petApi, "@Component");
}
@Test
public void testRestTemplateWithUseBeanValidationEnabled() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.USE_BEANVALIDATION, true);
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);
validateJavaSourceFiles(files);
Path pomFile = Paths.get(output + "/pom.xml");
TestUtils.assertFileContains(pomFile, "<artifactId>jakarta.validation-api</artifactId>");
Path petModel = Paths.get(output + "/src/main/java/org/openapitools/client/model/Pet.java");
TestUtils.assertFileContains(petModel, "@Valid");
}
@Test
public void testRestTemplateWithUseBeanValidationDisabled() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.USE_BEANVALIDATION, false);
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);
validateJavaSourceFiles(files);
Path pomFile = Paths.get(output + "/pom.xml");
TestUtils.assertFileNotContains(pomFile, "<artifactId>jakarta.validation-api</artifactId>");
Path petModel = Paths.get(output + "/src/main/java/org/openapitools/client/model/Pet.java");
TestUtils.assertFileNotContains(petModel, "@Valid");
}
@Test
public void testRestTemplateWithPerformBeanValidationEnabled() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.PERFORM_BEANVALIDATION, true);
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);
validateJavaSourceFiles(files);
Path pomFile = Paths.get(output + "/pom.xml");
TestUtils.assertFileContains(pomFile, "<artifactId>hibernate-validator</artifactId>");
Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/BeanValidationException.java");
TestUtils.assertFileExists(petApi);
}
@Test
public void testRestTemplateWithPerformBeanValidationDisabled() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.PERFORM_BEANVALIDATION, false);
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);
validateJavaSourceFiles(files);
Path pomFile = Paths.get(output + "/pom.xml");
TestUtils.assertFileNotContains(pomFile, "<artifactId>hibernate-validator</artifactId>");
Path petApi = Paths.get(output + "/src/main/java/org/openapitools/client/invoker/BeanValidationException.java");
TestUtils.assertFileNotExists(petApi);
}
@Test
public void testLogicToAvoidStackOverflow() throws IOException {
Map<String, Object> properties = new HashMap<>();

View File

@@ -64,13 +64,13 @@ public class JavaValidationArrayPrimitivesTest {
.withType("List<@Max(10) Integer>")
.toType()
.hasProperty("numberMinMax")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMin")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMax")
.withType("List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("stringPatternWithMin")
.withType("Set<@Pattern(regexp = \"^\\\\d{3}-\\\\d{2}-\\\\d{4}$\") @Size(min = 10) String>")
@@ -88,7 +88,7 @@ public class JavaValidationArrayPrimitivesTest {
.withType("Set<@Size(max = 1) String>")
.toType()
.hasProperty("stringNumbers")
.withType("Set<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("Set<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("intMinMaxNullable")
.withType("List<@Min(1) @Max(10) Integer>")
@@ -100,13 +100,13 @@ public class JavaValidationArrayPrimitivesTest {
.withType("List<@Max(10) Integer>")
.toType()
.hasProperty("numberMinMaxNullable")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMinNullable")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMaxNullable")
.withType("List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.withType("List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.toType();
}
@@ -138,13 +138,13 @@ public class JavaValidationArrayPrimitivesTest {
.withType("List<@Max(10) Integer>")
.toType()
.hasProperty("numberMinMax")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMin")
.withType("List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("numberMax")
.withType("List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("stringPatternWithMin")
.withType("JsonNullable<Set<@Pattern(regexp = \"^\\\\d{3}-\\\\d{2}-\\\\d{4}$\") @Size(min = 10) String>>")
@@ -162,7 +162,7 @@ public class JavaValidationArrayPrimitivesTest {
.withType("JsonNullable<Set<@Size(max = 1) String>>")
.toType()
.hasProperty("stringNumbers")
.withType("Set<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>")
.withType("Set<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>")
.toType()
.hasProperty("intMinMaxNullable")
.withType("JsonNullable<List<@Min(1) @Max(10) Integer>>")
@@ -174,13 +174,13 @@ public class JavaValidationArrayPrimitivesTest {
.withType("JsonNullable<List<@Max(10) Integer>>")
.toType()
.hasProperty("numberMinMaxNullable")
.withType("JsonNullable<List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>>")
.withType("JsonNullable<List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>>")
.toType()
.hasProperty("numberMinNullable")
.withType("JsonNullable<List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>>")
.withType("JsonNullable<List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>>")
.toType()
.hasProperty("numberMaxNullable")
.withType("JsonNullable<List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>>")
.withType("JsonNullable<List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>>")
.toType();
}

View File

@@ -973,6 +973,8 @@ public class SpringCodegenTest {
.withType( "Set<Integer>" );
}
@Test
public void shouldAddValidAnnotationIntoCollectionWhenBeanValidationIsEnabled_issue17150() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
@@ -1023,13 +1025,13 @@ public class SpringCodegenTest {
.withType( "List<@Max(10) Integer>" )
.toType()
.hasProperty("numberMinMax")
.withType( "List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>" )
.withType( "List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>" )
.toType()
.hasProperty("numberMin")
.withType( "List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>" )
.withType( "List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>" )
.toType()
.hasProperty("numberMax")
.withType( "List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>" )
.withType( "List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>" )
.toType()
.hasProperty("stringPatternNullable")
@@ -1054,13 +1056,13 @@ public class SpringCodegenTest {
.withType( "JsonNullable<List<@Max(10) Integer>>" )
.toType()
.hasProperty("numberMinMaxNullable")
.withType( "JsonNullable<List<@DecimalMin(value = \"1\", inclusive = true) @DecimalMax(value = \"10\", inclusive = true) BigDecimal>>" )
.withType( "JsonNullable<List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>>" )
.toType()
.hasProperty("numberMinNullable")
.withType( "JsonNullable<List<@DecimalMin(value = \"1\", inclusive = true) BigDecimal>>" )
.withType( "JsonNullable<List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>>" )
.toType()
.hasProperty("numberMaxNullable")
.withType( "JsonNullable<List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>>" )
.withType( "JsonNullable<List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>>" )
.toType()
;
}

View File

@@ -295,11 +295,10 @@ public class ModelUtilsTest {
Assert.assertEquals(decoded, "~1 Hallo/Welt");
}
// 3.0 spec tests
// 3.1 spec test
@Test
public void test30Schemas() {
final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/schema.yaml");
public void testIsMapSchema() {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_1/schema.yaml");
Schema misc = ModelUtils.getSchema(openAPI, "Misc");
// test map
@@ -309,61 +308,5 @@ public class ModelUtilsTest {
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_1")));
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_2")));
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_3")));
// test oneOf
Assert.assertTrue(ModelUtils.isOneOf((Schema) misc.getProperties().get("oneof1")));
// test anyOf model
Schema anyof1 = ModelUtils.getSchema(openAPI, "anyof1");
Assert.assertNotNull(anyof1);
Assert.assertNull(anyof1.getTypes());
Assert.assertNull(anyof1.getType());
Assert.assertTrue(ModelUtils.hasAnyOf(anyof1));
Assert.assertTrue(ModelUtils.isAnyOf(anyof1));
// test anyOf in properties
Schema anyof1Property = (Schema) misc.getProperties().get("anyof1");
Assert.assertNotNull(anyof1Property);
Assert.assertNull(anyof1Property.getTypes());
Assert.assertNull(anyof1Property.getType());
Assert.assertTrue(ModelUtils.hasAnyOf(anyof1Property));
Assert.assertTrue(ModelUtils.isAnyOf(anyof1Property));
}
// 3.1 spec tests
@Test
public void test31Schemas() {
final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_1/schema.yaml");
Schema misc = ModelUtils.getSchema(openAPI, "Misc");
// test map
Assert.assertTrue(ModelUtils.isMapSchema((Schema) misc.getProperties().get("map1")));
// test free form object
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_1")));
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_2")));
Assert.assertTrue(ModelUtils.isFreeFormObject((Schema) misc.getProperties().get("free_form_object_3")));
// test oneOf property
Assert.assertTrue(ModelUtils.isOneOf((Schema) misc.getProperties().get("oneof1")));
// test anyOf property
Schema anyof1 = (Schema) misc.getProperties().get("anyof1");
Assert.assertNotNull(anyof1);
Assert.assertNull(anyof1.getTypes());
Assert.assertNull(anyof1.getType());
Assert.assertNotNull(anyof1.getAnyOf());
Assert.assertFalse(anyof1.getAnyOf().isEmpty());
Assert.assertTrue(ModelUtils.hasAnyOf(anyof1));
Assert.assertTrue(ModelUtils.isAnyOf(anyof1));
Schema anyof2 = (Schema) misc.getProperties().get("anyof2");
Assert.assertNotNull(anyof2);
Assert.assertNull(anyof2.getTypes());
Assert.assertNull(anyof2.getType());
Assert.assertNotNull(anyof2.getAnyOf());
Assert.assertFalse(anyof2.getAnyOf().isEmpty());
Assert.assertTrue(ModelUtils.hasAnyOf(anyof2));
Assert.assertTrue(ModelUtils.isAnyOf(anyof2));
}
}

View File

@@ -978,23 +978,6 @@ paths:
$ref: '#/components/schemas/FreeFormObject'
description: request body
required: true
/fake/stringMap-reference:
post:
tags:
- fake
summary: test referenced string map
description: ''
operationId: testStringMapReference
responses:
'200':
description: successful operation
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/MapOfString'
description: request body
required: true
/fake/inline-additionalProperties:
post:
tags:
@@ -1828,11 +1811,6 @@ components:
type: object
description: A schema consisting only of additional properties
additionalProperties: true
MapOfString:
type: object
description: A schema consisting only of additional properties of type string
additionalProperties:
type: string
OuterEnum:
nullable: true
type: string

View File

@@ -991,23 +991,6 @@ paths:
$ref: '#/components/schemas/FreeFormObject'
description: request body
required: true
/fake/stringMap-reference:
post:
tags:
- fake
summary: test referenced string map
description: ''
operationId: testStringMapReference
responses:
'200':
description: successful operation
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/MapOfString'
description: request body
required: true
/fake/inline-additionalProperties:
post:
tags:
@@ -1959,11 +1942,6 @@ components:
type: object
description: A schema consisting only of additional properties
additionalProperties: true
MapOfString:
type: object
description: A schema consisting only of additional properties of type string
additionalProperties:
type: string
OuterEnum:
nullable: true
type: string

View File

@@ -544,26 +544,6 @@ paths:
text/plain:
schema:
type: string
/echo/body/string_enum:
post:
tags:
- body
summary: Test string enum response body
description: Test string enum response body
operationId: test/echo/body/string_enum
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/StringEnumRef'
description: String enum
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/StringEnumRef'
/binary/gif:
post:
tags:

View File

@@ -30,7 +30,6 @@ paths:
delete:
tags:
- person
x-internal: true
parameters:
- name: personId
in: path
@@ -58,10 +57,3 @@ components:
type: string
firstName:
type: string
Dummy:
x-internal: true
description: to test x-internal
type: object
properties:
test:
type: string

View File

@@ -1,46 +0,0 @@
get:
description: Test path parameter(s)
operationId: "tests/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}"
parameters:
- explode: false
in: path
name: path_string
required: true
schema:
type: string
style: simple
- explode: false
in: path
name: path_integer
required: true
schema:
type: integer
style: simple
- explode: false
in: path
name: enum_nonref_string_path
required: true
schema:
enum:
- success
- failure
- unclassified
type: string
style: simple
- explode: false
in: path
name: enum_ref_string_path
required: true
schema:
$ref: "../schemas/StringEnumRef.yaml"
style: simple
responses:
"200":
content:
text/plain:
schema:
type: string
description: Successful operation
summary: Test path parameter(s)
tags:
- path

View File

@@ -1,5 +0,0 @@
type: string
enum:
- success
- failure
- unclassified

Some files were not shown because too many files have changed in this diff Show More