diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md
index eee69cd87eae..bbe5289102ea 100644
--- a/docs/generators/dart-dio.md
+++ b/docs/generators/dart-dio.md
@@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
+|apiClientName|Specify the api client class name, defaults to 'ApiClient'| |ApiClient|
|dateLibrary|Specify Date library|
**core** [DEFAULT] Dart core library (DateTime) **timemachine** Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing. |core|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|**false** The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. **true** Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
diff --git a/docs/generators/dart.md b/docs/generators/dart.md
index cbc19071638a..14276964abe9 100644
--- a/docs/generators/dart.md
+++ b/docs/generators/dart.md
@@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
+|apiClientName|Specify the api client class name, defaults to 'ApiClient'| |ApiClient|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|**false** The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. **true** Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|**false** No changes to the enum's are made, this is the default option. **true** With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case. |false|
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java
index 91cc8141e2f0..84df51b522c0 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java
@@ -31,7 +31,7 @@ public class CodegenOperation {
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false,
hasErrorResponseObject; // if 4xx, 5xx responses have at least one error object defined
- public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType,
+ public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType, returnInnerType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public CodegenDiscriminator discriminator;
public List> consumes, produces, prioritizedContentTypes;
@@ -320,6 +320,7 @@ public String toString() {
sb.append(", returnType='").append(returnType).append('\'');
sb.append(", httpMethod='").append(httpMethod).append('\'');
sb.append(", returnBaseType='").append(returnBaseType).append('\'');
+ sb.append(", returnInnerType='").append(returnInnerType).append('\'');
sb.append(", returnContainer='").append(returnContainer).append('\'');
sb.append(", summary='").append(summary).append('\'');
sb.append(", unescapedNotes='").append(unescapedNotes).append('\'');
@@ -397,6 +398,7 @@ public boolean equals(Object o) {
Objects.equals(returnType, that.returnType) &&
Objects.equals(httpMethod, that.httpMethod) &&
Objects.equals(returnBaseType, that.returnBaseType) &&
+ Objects.equals(returnInnerType, that.returnInnerType) &&
Objects.equals(returnContainer, that.returnContainer) &&
Objects.equals(summary, that.summary) &&
Objects.equals(unescapedNotes, that.unescapedNotes) &&
@@ -442,7 +444,7 @@ public int hashCode() {
isArray, isMultipart, isResponseBinary, isResponseFile, isResponseOptional, hasReference,
hasDefaultResponse, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated, isCallbackRequest, uniqueItems, path, operationId, returnType, httpMethod,
- returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse,
+ returnBaseType, returnInnerType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse,
discriminator, consumes, produces, prioritizedContentTypes, servers, bodyParam, allParams, bodyParams,
pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, optionalParams,
authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs,
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
index e82ee5999cda..4792efab9f30 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
@@ -3907,9 +3907,11 @@ protected void handleMethodResponse(Operation operation,
ArraySchema as = (ArraySchema) responseSchema;
CodegenProperty innerProperty = fromProperty("response", getSchemaItems(as));
op.returnBaseType = innerProperty.baseType;
+ op.returnInnerType = innerProperty.dataType;
} else if (ModelUtils.isMapSchema(responseSchema)) {
CodegenProperty innerProperty = fromProperty("response", getAdditionalProperties(responseSchema));
op.returnBaseType = innerProperty.baseType;
+ op.returnInnerType = innerProperty.dataType;
} else {
if (cm.complexType != null) {
op.returnBaseType = cm.complexType;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
index 544d6d690890..a67d3882be44 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
@@ -7,6 +7,7 @@
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.servers.Server;
+import io.swagger.v3.oas.models.responses.ApiResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
@@ -45,6 +46,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
public static final String PUB_AUTHOR_EMAIL = "pubAuthorEmail";
public static final String PUB_HOMEPAGE = "pubHomepage";
public static final String USE_ENUM_EXTENSION = "useEnumExtension";
+ public static final String API_CLIENT_NAME = "apiClientName";
protected String pubLibrary = "openapi.api";
protected String pubName = "openapi";
@@ -60,6 +62,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
protected String modelDocPath = "doc" + File.separator;
protected String apiTestPath = "test" + File.separator;
protected String modelTestPath = "test" + File.separator;
+ protected String apiClientName = "ApiClient";
protected Map imports = new HashMap<>();
@@ -72,29 +75,22 @@ public AbstractDartCodegen() {
SecurityFeature.OAuth2_Implicit,
SecurityFeature.BasicAuth,
SecurityFeature.BearerToken,
- SecurityFeature.ApiKey
- ))
+ SecurityFeature.ApiKey))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
- GlobalFeature.ParameterStyling
- )
+ GlobalFeature.ParameterStyling)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism,
SchemaSupportFeature.Union,
- SchemaSupportFeature.Composite
- )
+ SchemaSupportFeature.Composite)
.includeParameterFeatures(
- ParameterFeature.Cookie
- )
+ ParameterFeature.Cookie)
.includeClientModificationFeatures(
- ClientModificationFeature.BasePath
- )
+ ClientModificationFeature.BasePath)
.excludeWireFormatFeatures(
- WireFormatFeature.XML
- )
- );
+ WireFormatFeature.XML));
outputFolder = "generated-code/dart";
modelTemplateFiles.put("model.mustache", ".dart");
@@ -109,7 +105,7 @@ public AbstractDartCodegen() {
apiTestTemplateFiles.put("api_test.mustache", ".dart");
final List reservedWordsList = new ArrayList<>();
- try(BufferedReader reader = new BufferedReader(
+ try (BufferedReader reader = new BufferedReader(
new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"),
StandardCharsets.UTF_8))) {
while (reader.ready()) {
@@ -126,8 +122,7 @@ public AbstractDartCodegen() {
"bool",
"int",
"num",
- "double"
- );
+ "double");
typeMapping = new HashMap<>();
typeMapping.put("Array", "List");
@@ -154,7 +149,7 @@ public AbstractDartCodegen() {
typeMapping.put("UUID", "String");
typeMapping.put("URI", "String");
typeMapping.put("ByteArray", "String");
- typeMapping.put("object", "Object");
+ typeMapping.put("object", "Map"); // prefer Dart Map for generic JSON objects
typeMapping.put("AnyType", "Object");
// Data types of the above values which are automatically imported
@@ -168,8 +163,7 @@ public AbstractDartCodegen() {
"Set",
"Map",
"DateTime",
- "Object"
- );
+ "Object");
imports.put("String", "dart:core");
imports.put("bool", "dart:core");
@@ -190,7 +184,9 @@ public AbstractDartCodegen() {
addOption(PUB_AUTHOR, "Author name in generated pubspec", pubAuthor);
addOption(PUB_AUTHOR_EMAIL, "Email address of the author in generated pubspec", pubAuthorEmail);
addOption(PUB_HOMEPAGE, "Homepage in generated pubspec", pubHomepage);
- addOption(USE_ENUM_EXTENSION, "Allow the 'x-enum-values' extension for enums", String.valueOf(useEnumExtension));
+ addOption(USE_ENUM_EXTENSION, "Allow the 'x-enum-values' extension for enums",
+ String.valueOf(useEnumExtension));
+ addOption(API_CLIENT_NAME, "Specify the api client class name, defaults to 'ApiClient'", apiClientName);
addOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder);
}
@@ -221,56 +217,58 @@ public void processOpts() {
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
- LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
- LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
+ LOGGER.info(
+ "Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
+ LOGGER.info(
+ "NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
}
if (additionalProperties.containsKey(PUB_NAME)) {
this.setPubName((String) additionalProperties.get(PUB_NAME));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_NAME, pubName);
}
if (additionalProperties.containsKey(PUB_LIBRARY)) {
this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_LIBRARY, pubLibrary);
}
if (additionalProperties.containsKey(PUB_VERSION)) {
this.setPubVersion((String) additionalProperties.get(PUB_VERSION));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_VERSION, pubVersion);
}
if (additionalProperties.containsKey(PUB_DESCRIPTION)) {
this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_DESCRIPTION, pubDescription);
}
if (additionalProperties.containsKey(PUB_AUTHOR)) {
this.setPubAuthor((String) additionalProperties.get(PUB_AUTHOR));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_AUTHOR, pubAuthor);
}
if (additionalProperties.containsKey(PUB_AUTHOR_EMAIL)) {
this.setPubAuthorEmail((String) additionalProperties.get(PUB_AUTHOR_EMAIL));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_AUTHOR_EMAIL, pubAuthorEmail);
}
if (additionalProperties.containsKey(PUB_HOMEPAGE)) {
this.setPubHomepage((String) additionalProperties.get(PUB_HOMEPAGE));
} else {
- //not set, use to be passed to template
+ // not set, use to be passed to template
additionalProperties.put(PUB_HOMEPAGE, pubHomepage);
}
@@ -281,6 +279,13 @@ public void processOpts() {
additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension);
}
+ if (additionalProperties.containsKey(API_CLIENT_NAME)) {
+ this.setApiClientName((String) additionalProperties.get(API_CLIENT_NAME));
+ } else {
+ // not set, use to be passed to template
+ additionalProperties.put(API_CLIENT_NAME, apiClientName);
+ }
+
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
String srcFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER);
this.setSourceFolder(srcFolder.replace('/', File.separatorChar));
@@ -309,7 +314,8 @@ protected boolean isReservedWord(String word) {
// * a keyword
// * a word that has been mapped in the reservedWordsMappings
// * a default included type or a type include through some library
- return super.isReservedWord(word) || reservedWordsMappings().containsKey(word) || defaultIncludes().contains(word);
+ return super.isReservedWord(word) || reservedWordsMappings().containsKey(word)
+ || defaultIncludes().contains(word);
}
@Override
@@ -322,12 +328,14 @@ public String escapeReservedWord(String name) {
@Override
public String apiFileFolder() {
- return (outputFolder + File.separator + libPath + sourceFolder + File.separator + apiPackage()).replace('/', File.separatorChar);
+ return (outputFolder + File.separator + libPath + sourceFolder + File.separator + apiPackage()).replace('/',
+ File.separatorChar);
}
@Override
public String modelFileFolder() {
- return (outputFolder + File.separator + libPath + sourceFolder + File.separator + modelPackage()).replace('/', File.separatorChar);
+ return (outputFolder + File.separator + libPath + sourceFolder + File.separator + modelPackage()).replace('/',
+ File.separatorChar);
}
@Override
@@ -358,6 +366,12 @@ public String toVarName(String name) {
// always need to replace leading underscores first
name = name.replaceAll("^_", "");
+ // if the query var was an underscore, the name is now empty.
+ // fix that with a valid Dart variable name and hope it doesn't conflict.
+ if (name.matches("")) {
+ name = "q";
+ }
+
// if it's all upper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
@@ -433,7 +447,8 @@ public String toModelName(final String name) {
// model name starts with number
if (camelizedName.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
- LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, modelName);
+ LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name,
+ modelName);
return modelName;
}
@@ -445,7 +460,8 @@ public String toModelFilename(String name) {
return underscore(toModelName(name));
}
- @Override public String toModelDocFilename(String name) {
+ @Override
+ public String toModelDocFilename(String name) {
return toModelName(name);
}
@@ -495,17 +511,23 @@ public String getTypeDeclaration(Schema p) {
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
}
if (ModelUtils.isMapSchema(target)) {
- // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
+ // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that
+ // also defines
// additionalproperties: true
Schema> inner = getAdditionalProperties(target);
if (inner == null) {
- LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName());
+ LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string",
+ p.getName());
inner = new StringSchema().description("TODO default missing map inner type to string");
p.setAdditionalProperties(inner);
}
return getSchemaType(target) + "";
}
- return super.getTypeDeclaration(p);
+
+ // this code duplicates what is in the super class, so we don't call super
+ // anymore
+ // return super.getTypeDeclaration(p);
+ return getSchemaType(p);
}
@Override
@@ -529,17 +551,22 @@ public ModelsMap postProcessModels(ModelsMap objs) {
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if (!model.isEnum && property.isEnum && property.getComposedSchemas() == null) {
- // These are inner enums, enums which do not exist as models, just as properties.
+ // These are inner enums, enums which do not exist as models, just as
+ // properties.
// They are handled via the enum_inline template and are generated in the
- // same file as the containing class. To prevent name clashes the inline enum classes
+ // same file as the containing class. To prevent name clashes the inline enum
+ // classes
// are prefix with the classname of the containing class in the template.
- // Here the datatypeWithEnum template variable gets updated to match that scheme.
- // Also taking into account potential collection types e.g. List -> List
+ // Here the datatypeWithEnum template variable gets updated to match that
+ // scheme.
+ // Also taking into account potential collection types e.g. List
+ // -> List
final String enumName = model.classname + property.enumName;
if (property.items != null) {
// inner items e.g. enums in collections, only works for one level
// but same is the case for DefaultCodegen
- property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.items.datatypeWithEnum, enumName));
+ property.setDatatypeWithEnum(
+ property.datatypeWithEnum.replace(property.items.datatypeWithEnum, enumName));
property.items.setDatatypeWithEnum(enumName);
property.items.setEnumName(enumName);
} else {
@@ -585,8 +612,10 @@ public CodegenProperty fromProperty(String name, Schema p) {
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) {
final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
for (CodegenResponse r : op.responses) {
- // By default, only set types are automatically added to operation imports, not sure why.
- // Add all container type imports here, by default 'dart:core' imports are skipped
+ // By default, only set types are automatically added to operation imports, not
+ // sure why.
+ // Add all container type imports here, by default 'dart:core' imports are
+ // skipped
// but other sub-classes may require specific container type imports.
if (r.containerType != null && typeMapping().containsKey(r.containerType)) {
final String value = typeMapping().get(r.containerType);
@@ -629,7 +658,9 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List> prioritizeContentTypes(List> enumVars, Map vendorExtensions, String dataType) {
+ protected void updateEnumVarsWithExtensions(List> enumVars,
+ Map vendorExtensions, String dataType) {
if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) {
// Use the x-enum-values extension for this enum
// Existing enumVars added by the default handling need to be removed first
@@ -732,7 +764,8 @@ public String toOperationId(String operationId) {
// operationId starts with a number
if (operationId.matches("^\\d.*")) {
String newOperationId = camelize("call_" + operationId, true);
- LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, newOperationId);
+ LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId,
+ newOperationId);
operationId = newOperationId;
}
@@ -771,6 +804,10 @@ public void setUseEnumExtension(boolean useEnumExtension) {
this.useEnumExtension = useEnumExtension;
}
+ public void setApiClientName(String apiClientName) {
+ this.apiClientName = apiClientName;
+ }
+
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@@ -819,5 +856,7 @@ public void postProcessFile(File file, String fileType) {
}
@Override
- public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.DART; }
+ public GeneratorLanguage generatorLanguage() {
+ return GeneratorLanguage.DART;
+ }
}
diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache
index ba99ace33f36..cfb6f6855e6a 100644
--- a/modules/openapi-generator/src/main/resources/dart2/README.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache
@@ -55,27 +55,27 @@ import 'package:{{{pubName}}}/api.dart';
{{#isBasic}}
{{#isBasicBasic}}
// TODO Configure HTTP basic authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME'
-//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME'
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD';
{{/isBasicBasic}}
{{#isBasicBearer}}
// TODO Configure HTTP Bearer authorization: {{{name}}}
// Case 1. Use String Token
-//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN');
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN');
// Case 2. Use Function which generate token.
// String yourTokenGeneratorFunction() { ... }
-//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction);
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction);
{{/isBasicBearer}}
{{/isBasic}}
{{#isApiKey}}
// TODO Configure API key authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
-//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer';
{{/isApiKey}}
{{#isOAuth}}
// TODO Configure OAuth2 access token for authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache
index e40ebac39408..8656016497eb 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache
@@ -3,9 +3,9 @@
{{#operations}}
class {{{classname}}} {
- {{{classname}}}([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient;
+ {{{classname}}}([{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}? apiClient]) : apiClient = apiClient ?? default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}};
- final ApiClient apiClient;
+ final {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}} apiClient;
{{#operation}}
{{#summary}}
@@ -57,7 +57,7 @@ class {{{classname}}} {
// ignore: prefer_final_locals
Object? postBody{{#bodyParam}} = {{{paramName}}}{{/bodyParam}};
- final queryParams = [];
+ final queryParams = <{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}>[];
final headerParams = {};
final formParams = {};
{{#hasQueryParams}}
@@ -164,7 +164,7 @@ class {{{classname}}} {
Future<{{#returnType}}{{{.}}}?{{/returnType}}{{^returnType}}void{{/returnType}}> {{{nickname}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}}? {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async {
final response = await {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}} {{#allParams}}{{^required}}{{{paramName}}}: {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} {{/hasOptionalParams}});
if (response.statusCode >= HttpStatus.badRequest) {
- throw ApiException(response.statusCode, await _decodeBodyBytes(response));
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}(response.statusCode, await _decodeBodyBytes(response));
}
{{#returnType}}
// When a remote server returns no body with a status of 204, we shall not decode it.
@@ -175,7 +175,7 @@ class {{{classname}}} {
{{#isArray}}
final responseBody = await _decodeBodyBytes(response);
return (await apiClient.deserializeAsync(responseBody, '{{{returnType}}}') as List)
- .cast<{{{returnBaseType}}}>()
+ .cast<{{{returnInnerType}}}>()
.{{#uniqueItems}}toSet(){{/uniqueItems}}{{^uniqueItems}}toList(){{/uniqueItems}};
{{/isArray}}
{{^isArray}}
diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
index d8db09013b90..7b3fa6f35022 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
@@ -1,7 +1,7 @@
{{>header}}
{{>part_of}}
-class ApiClient {
- ApiClient({this.basePath = '{{{basePath}}}', this.authentication});
+class {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}} {
+ {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}({this.basePath = '{{{basePath}}}', this.authentication});
final String basePath;
@@ -18,7 +18,7 @@ class ApiClient {
}
final _defaultHeaderMap = {};
- final Authentication? authentication;
+ final {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}}? authentication;
void addDefaultHeader(String key, String value) {
_defaultHeaderMap[key] = value;
@@ -31,7 +31,7 @@ class ApiClient {
Future invokeAPI(
String path,
String method,
- List queryParams,
+ List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams,
Object? body,
Map headerParams,
Map formParams,
@@ -44,8 +44,8 @@ class ApiClient {
headerParams['Content-Type'] = contentType;
}
- final urlEncodedQueryParams = queryParams.map((param) => '$param');
- final queryString = urlEncodedQueryParams.isNotEmpty ? '?${urlEncodedQueryParams.join('&')}' : '';
+ final urlEncoded{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}s = queryParams.map((param) => '$param');
+ final queryString = urlEncoded{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}s.isNotEmpty ? '?${urlEncoded{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}s.join('&')}' : '';
final uri = Uri.parse('$basePath$path$queryString');
try {
@@ -92,35 +92,35 @@ class ApiClient {
case 'GET': return await _client.get(uri, headers: nullableHeaderParams,);
}
} on SocketException catch (error, trace) {
- throw ApiException.withInner(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(
HttpStatus.badRequest,
'Socket operation failed: $method $path',
error,
trace,
);
} on TlsException catch (error, trace) {
- throw ApiException.withInner(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(
HttpStatus.badRequest,
'TLS/SSL communication failed: $method $path',
error,
trace,
);
} on IOException catch (error, trace) {
- throw ApiException.withInner(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(
HttpStatus.badRequest,
'I/O operation failed: $method $path',
error,
trace,
);
} on ClientException catch (error, trace) {
- throw ApiException.withInner(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(
HttpStatus.badRequest,
'HTTP connection failed: $method $path',
error,
trace,
);
} on Exception catch (error, trace) {
- throw ApiException.withInner(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(
HttpStatus.badRequest,
'Exception occurred: $method $path',
error,
@@ -128,7 +128,7 @@ class ApiClient {
);
}
- throw ApiException(
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}(
HttpStatus.badRequest,
'Invalid HTTP operation: $method $path',
);
@@ -159,7 +159,7 @@ class ApiClient {
/// Update query and header parameters based on authentication settings.
void _updateParamsForAuth(
- List queryParams,
+ List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams,
Map headerParams,
) {
if (authentication != null) {
@@ -216,9 +216,9 @@ class ApiClient {
}
}
} on Exception catch (error, trace) {
- throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,);
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,);
}
- throw ApiException(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',);
+ throw {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',);
}
{{/native_serialization}}
}
@@ -250,7 +250,7 @@ Future deserializeAsync(DeserializationMessage message) async {
// If the expected target type is String, nothing to do...
return targetType == 'String'
? message.json
- : ApiClient._deserialize(
+ : {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}._deserialize(
jsonDecode(message.json),
targetType,
growable: message.growable,
diff --git a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache
index 3332ff1f205d..50c589b1bc30 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache
@@ -30,27 +30,27 @@ import 'package:{{{pubName}}}/api.dart';
{{#isBasic}}
{{#isBasicBasic}}
// TODO Configure HTTP basic authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME'
-//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME'
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD';
{{/isBasicBasic}}
{{#isBasicBearer}}
// TODO Configure HTTP Bearer authorization: {{{name}}}
// Case 1. Use String Token
-//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN');
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN');
// Case 2. Use Function which generate token.
// String yourTokenGeneratorFunction() { ... }
-//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction);
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction);
{{/isBasicBearer}}
{{/isBasic}}
{{#isApiKey}}
// TODO Configure API key authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
-//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer';
{{/isApiKey}}
{{#isOAuth}}
// TODO Configure OAuth2 access token for authorization: {{{name}}}
-//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN';
+//default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
diff --git a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache
index aeb7aa9ce226..445dcc89b535 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache
@@ -1,9 +1,9 @@
{{>header}}
{{>part_of}}
-class ApiException implements Exception {
- ApiException(this.code, this.message);
+class {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}} implements Exception {
+ {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}(this.code, this.message);
- ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace);
+ {{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}.withInner(this.code, this.message, this.innerException, this.stackTrace);
int code = 0;
String? message;
@@ -13,11 +13,11 @@ class ApiException implements Exception {
@override
String toString() {
if (message == null) {
- return 'ApiException';
+ return '{{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}}';
}
if (innerException == null) {
- return 'ApiException $code: $message';
+ return '{{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}} $code: $message';
}
- return 'ApiException $code: $message (Inner exception: $innerException)\n\n$stackTrace';
+ return '{{{modelNamePrefix}}}ApiException{{{modelNameSuffix}}} $code: $message (Inner exception: $innerException)\n\n$stackTrace';
}
}
diff --git a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache
index ec98b7d1d741..df3080bf2771 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache
@@ -1,7 +1,7 @@
{{>header}}
{{>part_of}}
-class QueryParam {
- const QueryParam(this.name, this.value);
+class {{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}} {
+ const {{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}(this.name, this.value);
final String name;
final String value;
@@ -11,15 +11,15 @@ class QueryParam {
}
// Ported from the Java version.
-Iterable _queryParams(String collectionFormat, String name, dynamic value,) {
+Iterable<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> _queryParams(String collectionFormat, String name, dynamic value,) {
// Assertions to run in debug mode only.
assert(name.isNotEmpty, 'Parameter cannot be an empty string.');
- final params = [];
+ final params = <{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}>[];
if (value is List) {
if (collectionFormat == 'multi') {
- return value.map((dynamic v) => QueryParam(name, parameterToString(v)),);
+ return value.map((dynamic v) => {{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}(name, parameterToString(v)),);
}
// Default collection format is 'csv'.
@@ -29,9 +29,9 @@ Iterable _queryParams(String collectionFormat, String name, dynamic
final delimiter = _delimiters[collectionFormat] ?? ',';
- params.add(QueryParam(name, value.map(parameterToString).join(delimiter),));
+ params.add({{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}(name, value.map(parameterToString).join(delimiter),));
} else if (value != null) {
- params.add(QueryParam(name, parameterToString(value)));
+ params.add({{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}(name, parameterToString(value)));
}
return params;
diff --git a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache
index 2fcebda4ea46..f87ec29ad2a4 100644
--- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache
@@ -30,4 +30,12 @@ final _regList = RegExp(r'^List<(.*)>$');
final _regSet = RegExp(r'^Set<(.*)>$');
final _regMap = RegExp(r'^Map$');
-ApiClient defaultApiClient = ApiClient();
+/// also add individual apis as getters on the primary default api client
+extension {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}Extension on {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}} {
+ {{#apiInfo}}{{#apis}}
+ {{{classname}}} get {{{classVarName}}} => {{{classname}}}(this);
+ {{/apis}}{{/apiInfo}}
+}
+
+
+{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}} default{{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}} = {{#apiClientName}}{{.}}{{/apiClientName}}{{^apiClientName}}{{{modelNamePrefix}}}ApiClient{{{modelNameSuffix}}}{{/apiClientName}}();
diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache
index b4f5a4587246..30bc5a6ecd43 100644
--- a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache
@@ -1,7 +1,7 @@
{{>header}}
{{>part_of}}
-class ApiKeyAuth implements Authentication {
- ApiKeyAuth(this.location, this.paramName);
+class {{{modelNamePrefix}}}ApiKeyAuth{{{modelNameSuffix}}} implements {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}} {
+ {{{modelNamePrefix}}}ApiKeyAuth{{{modelNameSuffix}}}(this.location, this.paramName);
final String location;
final String paramName;
@@ -10,12 +10,12 @@ class ApiKeyAuth implements Authentication {
String apiKey = '';
@override
- void applyToParams(List queryParams, Map headerParams) {
+ void applyToParams(List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams, Map headerParams) {
final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey';
if (paramValue.isNotEmpty) {
if (location == 'query') {
- queryParams.add(QueryParam(paramName, paramValue));
+ queryParams.add({{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}(paramName, paramValue));
} else if (location == 'header') {
headerParams[paramName] = paramValue;
} else if (location == 'cookie') {
diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache
index e8aaaa4d5411..0704665327f8 100644
--- a/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache
@@ -1,7 +1,7 @@
{{>header}}
{{>part_of}}
// ignore: one_member_abstracts
-abstract class Authentication {
+abstract class {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}} {
/// Apply authentication settings to header and query params.
- void applyToParams(List queryParams, Map headerParams);
+ void applyToParams(List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams, Map headerParams);
}
diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache
index 544219733921..1d39280f45c9 100644
--- a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache
@@ -1,13 +1,13 @@
{{>header}}
{{>part_of}}
-class HttpBasicAuth implements Authentication {
- HttpBasicAuth({this.username = '', this.password = ''});
+class {{{modelNamePrefix}}}HttpBasicAuthentication{{{modelNameSuffix}}} implements {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}} {
+ {{{modelNamePrefix}}}HttpBasicAuthentication{{{modelNameSuffix}}}({this.username = '', this.password = ''});
String username;
String password;
@override
- void applyToParams(List queryParams, Map headerParams) {
+ void applyToParams(List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams, Map headerParams) {
if (username.isNotEmpty && password.isNotEmpty) {
final credentials = '$username:$password';
headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}';
diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache
index 7c480c5e81d3..0b56af1726a2 100644
--- a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache
@@ -1,23 +1,29 @@
{{>header}}
{{>part_of}}
-typedef HttpBearerAuthProvider = String Function();
+typedef {{{modelNamePrefix}}}HttpBearerAuthProvider{{{modelNameSuffix}}} = String Function();
-class HttpBearerAuth implements Authentication {
- HttpBearerAuth();
+class {{{modelNamePrefix}}}HttpBearerAuthentication{{{modelNameSuffix}}} implements {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}} {
+
+ /// Constucts [HttpBearerAuthentication] from an optional [accessToken] which will be included in request headers
+ /// using the `Authorization: Bearer [token]` method.
+ {{{modelNamePrefix}}}HttpBearerAuthentication{{{modelNameSuffix}}}([dynamic accessToken]) {
+ this.accessToken = accessToken;
+ }
dynamic _accessToken;
dynamic get accessToken => _accessToken;
+ /// may be a String or a Function that returns a string.
set accessToken(dynamic accessToken) {
- if (accessToken is! String && accessToken is! HttpBearerAuthProvider) {
+ if (accessToken is! String && accessToken is! {{{modelNamePrefix}}}HttpBearerAuthProvider{{{modelNameSuffix}}}) {
throw ArgumentError('accessToken value must be either a String or a String Function().');
}
_accessToken = accessToken;
}
@override
- void applyToParams(List queryParams, Map headerParams) {
+ void applyToParams(List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams, Map headerParams) {
if (_accessToken == null) {
return;
}
@@ -26,7 +32,7 @@ class HttpBearerAuth implements Authentication {
if (_accessToken is String) {
accessToken = _accessToken;
- } else if (_accessToken is HttpBearerAuthProvider) {
+ } else if (_accessToken is {{{modelNamePrefix}}}HttpBearerAuthProvider{{{modelNameSuffix}}}) {
accessToken = _accessToken!();
} else {
return;
diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache
index c5c64d522184..b108f1a35cfc 100644
--- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache
@@ -1,12 +1,12 @@
{{>header}}
{{>part_of}}
-class OAuth implements Authentication {
- OAuth({this.accessToken = ''});
+class {{{modelNamePrefix}}}OAuth{{{modelNameSuffix}}} implements {{{modelNamePrefix}}}Authentication{{{modelNameSuffix}}} {
+ {{{modelNamePrefix}}}OAuth{{{modelNameSuffix}}}({this.accessToken = ''});
String accessToken;
@override
- void applyToParams(List queryParams, Map headerParams) {
+ void applyToParams(List<{{{modelNamePrefix}}}QueryParam{{{modelNameSuffix}}}> queryParams, Map headerParams) {
if (accessToken.isNotEmpty) {
headerParams['Authorization'] = 'Bearer $accessToken';
}
diff --git a/modules/openapi-generator/src/main/resources/dart2/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/dart2/git_push.sh.mustache
old mode 100755
new mode 100644
diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache
index 872dc9e8ee7c..d8549662f09a 100644
--- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache
@@ -164,7 +164,7 @@ class {{{classname}}} {
{{^items.isArray}}
{{#items.isMap}}
{{#items.complexType}}
- {{{name}}}: {{items.complexType}}.mapFromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}},
+ {{{name}}}: {{items.complexType}}.mapFromJson(json[r'{{{baseName}}}']{{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}),
{{/items.complexType}}
{{^items.complexType}}
{{{name}}}: mapCastOfType(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}},
@@ -172,7 +172,7 @@ class {{{classname}}} {
{{/items.isMap}}
{{^items.isMap}}
{{#items.complexType}}
- {{{name}}}: {{{items.complexType}}}.mapFromJson(json[r'{{{baseName}}}'{{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}}]) ?? {{{.}}}{{/defaultValue}}{{/required}},
+ {{{name}}}: {{{items.complexType}}}.mapFromJson(json[r'{{{baseName}}}']{{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}),
{{/items.complexType}}
{{^items.complexType}}
{{{name}}}: mapCastOfType(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}},
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java
index 1b268561e52a..828b5d6d0d7a 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientOptionsTest.java
@@ -49,6 +49,7 @@ protected void verifyOptions() {
verify(clientCodegen).setPubAuthorEmail(DartClientOptionsProvider.PUB_AUTHOR_EMAIL_VALUE);
verify(clientCodegen).setPubHomepage(DartClientOptionsProvider.PUB_HOMEPAGE_VALUE);
verify(clientCodegen).setSourceFolder(DartClientOptionsProvider.SOURCE_FOLDER_VALUE);
+ verify(clientCodegen).setApiClientName(DartClientOptionsProvider.API_CLIENT_NAME_VALUE);
verify(clientCodegen).setUseEnumExtension(Boolean.parseBoolean(DartClientOptionsProvider.USE_ENUM_EXTENSION));
verify(clientCodegen).setEnumUnknownDefaultCase(Boolean.parseBoolean(DartClientOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE));
}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java
index 03848b4f802b..50e61649a953 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartModelTest.java
@@ -33,7 +33,7 @@
@SuppressWarnings("static-method")
public class DartModelTest {
- @Test(description = "convert a simple php model")
+ @Test(description = "convert a simple dart model")
public void simpleModelTest() {
final Schema model = new Schema()
.description("a sample model")
@@ -46,12 +46,15 @@ public void simpleModelTest() {
.addRequiredItem("id")
.addRequiredItem("name");
final DefaultCodegen codegen = new DartClientCodegen();
+ codegen.setModelNamePrefix("Prefix");
+ codegen.setModelNameSuffix("Suffix");
+
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
- Assert.assertEquals(cm.classname, "Sample");
+ Assert.assertEquals(cm.classname, "PrefixSampleSuffix");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 6);
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientOptionsTest.java
index 2292d1109898..8ebe7468f085 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientOptionsTest.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientOptionsTest.java
@@ -48,6 +48,7 @@ protected void verifyOptions() {
verify(clientCodegen).setPubAuthorEmail(DartDioClientOptionsProvider.PUB_AUTHOR_EMAIL_VALUE);
verify(clientCodegen).setPubHomepage(DartDioClientOptionsProvider.PUB_HOMEPAGE_VALUE);
verify(clientCodegen).setSourceFolder(DartDioClientOptionsProvider.SOURCE_FOLDER_VALUE);
+ verify(clientCodegen).setApiClientName(DartDioClientOptionsProvider.API_CLIENT_NAME_VALUE);
verify(clientCodegen).setUseEnumExtension(Boolean.parseBoolean(DartDioClientOptionsProvider.USE_ENUM_EXTENSION));
verify(clientCodegen).setDateLibrary(DartDioClientCodegen.DATE_LIBRARY_DEFAULT);
verify(clientCodegen).setLibrary(DartDioClientCodegen.SERIALIZATION_LIBRARY_DEFAULT);
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java
index 5e468090bed6..db003c62ae64 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java
@@ -40,6 +40,7 @@ public class DartClientOptionsProvider implements OptionsProvider {
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
public static final String ENUM_UNKNOWN_DEFAULT_CASE_VALUE = "false";
+ public static final String API_CLIENT_NAME_VALUE = "ApiClient";
@Override
public String getLanguage() {
@@ -59,6 +60,7 @@ public Map createOptions() {
.put(DartClientCodegen.PUB_AUTHOR, PUB_AUTHOR_VALUE)
.put(DartClientCodegen.PUB_AUTHOR_EMAIL, PUB_AUTHOR_EMAIL_VALUE)
.put(DartClientCodegen.PUB_HOMEPAGE, PUB_HOMEPAGE_VALUE)
+ .put(DartClientCodegen.API_CLIENT_NAME, API_CLIENT_NAME_VALUE)
.put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
.put(DartClientCodegen.USE_ENUM_EXTENSION, USE_ENUM_EXTENSION)
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java
index 0072e04e0c15..077ee62492c2 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java
@@ -37,6 +37,7 @@ public class DartDioClientOptionsProvider implements OptionsProvider {
public static final String PUB_AUTHOR_VALUE = "Author";
public static final String PUB_AUTHOR_EMAIL_VALUE = "author@homepage";
public static final String PUB_HOMEPAGE_VALUE = "Homepage";
+ public static final String API_CLIENT_NAME_VALUE = "ApiClient";
public static final String ENUM_UNKNOWN_DEFAULT_CASE_VALUE = "false";
@Override
@@ -57,6 +58,7 @@ public Map createOptions() {
.put(DartDioClientCodegen.PUB_AUTHOR, PUB_AUTHOR_VALUE)
.put(DartDioClientCodegen.PUB_AUTHOR_EMAIL, PUB_AUTHOR_EMAIL_VALUE)
.put(DartDioClientCodegen.PUB_HOMEPAGE, PUB_HOMEPAGE_VALUE)
+ .put(DartDioClientCodegen.API_CLIENT_NAME, API_CLIENT_NAME_VALUE)
.put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioClientCodegen.SERIALIZATION_LIBRARY_DEFAULT)
.put(DartDioClientCodegen.DATE_LIBRARY, DartDioClientCodegen.DATE_LIBRARY_DEFAULT)
.put(DartDioClientCodegen.FINAL_PROPERTIES, DartDioClientCodegen.FINAL_PROPERTIES_DEFAULT_VALUE)
diff --git a/openapi-generator.code-workspace b/openapi-generator.code-workspace
index 94b0864b5d8d..0b764e515730 100644
--- a/openapi-generator.code-workspace
+++ b/openapi-generator.code-workspace
@@ -26,7 +26,7 @@
},
],
"settings": {
- "editor.formatOnType": true,
+ "editor.formatOnType": false,
"editor.linkedEditing": true,
"editor.tabCompletion": "on",
"editor.tabSize": 4,
@@ -35,7 +35,6 @@
"editor.suggestSelection": "first",
"editor.semanticHighlighting.enabled": true,
"explorer.confirmDelete": true,
-
"files.autoSave": "onFocusChange",
"files.exclude": {
"**/.classpath": true,
@@ -45,24 +44,22 @@
},
"files.trimFinalNewlines": false,
"files.trimTrailingWhitespace": true,
-
"task.saveBeforeRun": "always",
-
"java.autobuild.enabled": false,
"java.completion.enabled": true,
"java.completion.guessMethodArguments": true,
"java.completion.maxResults": 5,
"java.format.onType.enabled": true,
-
"java.referencesCodeLens.enabled": true,
"java.saveActions.organizeImports": true,
"java.showBuildStatusOnStart.enabled": true,
-
"java.dependency.autoRefresh": true,
"java.dependency.refreshDelay": 3000,
"java.format.enabled": true,
-
"maven.pomfile.autoUpdateEffectivePOM": true,
+ "workspace.isHidden": false,
+ "editor.formatOnSave": false,
+ "editor.formatOnPaste": false,
},
"extensions": {
"recommendations": [
@@ -72,7 +69,6 @@
"visualstudioexptteam.vscodeintellicode",
"42crunch.vscode-openapi",
"mermade.openapi-lint"
-
]
}
-}
\ No newline at end of file
+}
diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/NullableClass.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/NullableClass.md
index 70ac1091d417..31bca081ade2 100644
--- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/NullableClass.md
+++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/NullableClass.md
@@ -14,12 +14,12 @@ Name | Type | Description | Notes
**stringProp** | **String** | | [optional]
**dateProp** | [**DateTime**](DateTime.md) | | [optional]
**datetimeProp** | [**DateTime**](DateTime.md) | | [optional]
-**arrayNullableProp** | **List<Object>** | | [optional]
-**arrayAndItemsNullableProp** | **List<Object>** | | [optional]
-**arrayItemsNullable** | **List<Object>** | | [optional]
-**objectNullableProp** | **Map<String, Object>** | | [optional]
-**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional]
-**objectItemsNullable** | **Map<String, Object>** | | [optional]
+**arrayNullableProp** | [**List<Map>**](Map.md) | | [optional]
+**arrayAndItemsNullableProp** | [**List<Map>**](Map.md) | | [optional]
+**arrayItemsNullable** | [**List<Map>**](Map.md) | | [optional]
+**objectNullableProp** | [**Map<String, Map>**](Map.md) | | [optional]
+**objectAndItemsNullableProp** | [**Map<String, Map>**](Map.md) | | [optional]
+**objectItemsNullable** | [**Map<String, Map>**](Map.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart
index 3816bb33839e..307479401847 100644
--- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart
+++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart
@@ -122,7 +122,7 @@ class NullableClass {
)
- final List? arrayNullableProp;
+ final List? arrayNullableProp;
@@ -134,7 +134,7 @@ class NullableClass {
)
- final List? arrayAndItemsNullableProp;
+ final List? arrayAndItemsNullableProp;
@@ -146,7 +146,7 @@ class NullableClass {
)
- final List? arrayItemsNullable;
+ final List? arrayItemsNullable;
@@ -158,7 +158,7 @@ class NullableClass {
)
- final Map? objectNullableProp;
+ final Map? objectNullableProp;
@@ -170,7 +170,7 @@ class NullableClass {
)
- final Map? objectAndItemsNullableProp;
+ final Map? objectAndItemsNullableProp;
@@ -182,7 +182,7 @@ class NullableClass {
)
- final Map? objectItemsNullable;
+ final Map? objectItemsNullable;
diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/NullableClass.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/NullableClass.md
index 9b2e46df0a09..c190f0ab458f 100644
--- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/NullableClass.md
+++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/NullableClass.md
@@ -14,12 +14,12 @@ Name | Type | Description | Notes
**stringProp** | **String** | | [optional]
**dateProp** | [**DateTime**](DateTime.md) | | [optional]
**datetimeProp** | [**DateTime**](DateTime.md) | | [optional]
-**arrayNullableProp** | [**List**](Object.md) | | [optional] [default to const []]
-**arrayAndItemsNullableProp** | [**List**](Object.md) | | [optional] [default to const []]
-**arrayItemsNullable** | [**List**](Object.md) | | [optional] [default to const []]
-**objectNullableProp** | [**Map**](Object.md) | | [optional] [default to const {}]
-**objectAndItemsNullableProp** | [**Map**](Object.md) | | [optional] [default to const {}]
-**objectItemsNullable** | [**Map**](Object.md) | | [optional] [default to const {}]
+**arrayNullableProp** | [**List**](Map.md) | | [optional] [default to const []]
+**arrayAndItemsNullableProp** | [**List**](Map.md) | | [optional] [default to const []]
+**arrayItemsNullable** | [**List**](Map.md) | | [optional] [default to const []]
+**objectNullableProp** | [**Map**](Map.md) | | [optional] [default to const {}]
+**objectAndItemsNullableProp** | [**Map**](Map.md) | | [optional] [default to const {}]
+**objectItemsNullable** | [**Map**](Map.md) | | [optional] [default to const {}]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart
index b8a0878b3056..85bc0f870adc 100644
--- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart
+++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart
@@ -39,17 +39,17 @@ class NullableClass {
DateTime? datetimeProp;
- List? arrayNullableProp;
+ List? arrayNullableProp;
- List? arrayAndItemsNullableProp;
+ List? arrayAndItemsNullableProp;
- List arrayItemsNullable;
+ List arrayItemsNullable;
- Map? objectNullableProp;
+ Map? objectNullableProp;
- Map? objectAndItemsNullableProp;
+ Map? objectAndItemsNullableProp;
- Map objectItemsNullable;
+ Map objectItemsNullable;
@override
bool operator ==(Object other) => identical(this, other) || other is NullableClass &&
@@ -149,12 +149,12 @@ class NullableClass {
stringProp: mapValueOfType(json, r'string_prop'),
dateProp: mapDateTime(json, r'date_prop', ''),
datetimeProp: mapDateTime(json, r'datetime_prop', ''),
- arrayNullableProp: Object.listFromJson(json[r'array_nullable_prop']) ?? const [],
- arrayAndItemsNullableProp: Object.listFromJson(json[r'array_and_items_nullable_prop']) ?? const [],
- arrayItemsNullable: Object.listFromJson(json[r'array_items_nullable']) ?? const [],
- objectNullableProp: mapCastOfType(json, r'object_nullable_prop') ?? const {},
- objectAndItemsNullableProp: mapCastOfType(json, r'object_and_items_nullable_prop') ?? const {},
- objectItemsNullable: mapCastOfType(json, r'object_items_nullable') ?? const {},
+ arrayNullableProp: Map.listFromJson(json[r'array_nullable_prop']) ?? const [],
+ arrayAndItemsNullableProp: Map.listFromJson(json[r'array_and_items_nullable_prop']) ?? const [],
+ arrayItemsNullable: Map.listFromJson(json[r'array_items_nullable']) ?? const [],
+ objectNullableProp: mapCastOfType(json, r'object_nullable_prop') ?? const {},
+ objectAndItemsNullableProp: mapCastOfType(json, r'object_and_items_nullable_prop') ?? const {},
+ objectItemsNullable: mapCastOfType(json, r'object_items_nullable') ?? const {},
);
}
return null;