diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index 076f92f6b8e6..f10e875630a7 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |pubAuthorEmail|Email address of the author in generated pubspec| |null| |pubDescription|Description in generated pubspec| |null| |pubHomepage|Homepage in generated pubspec| |null| +|pubLibrary|Library name in generated code| |null| |pubName|Name in generated pubspec| |null| |pubVersion|Version in generated pubspec| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/dart-jaguar.md b/docs/generators/dart-jaguar.md index e3c30cc7a1f7..017dff4c4f81 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |pubAuthorEmail|Email address of the author in generated pubspec| |null| |pubDescription|Description in generated pubspec| |null| |pubHomepage|Homepage in generated pubspec| |null| +|pubLibrary|Library name in generated code| |null| |pubName|Name in generated pubspec| |null| |pubVersion|Version in generated pubspec| |null| |serialization|Choose serialization format JSON or PROTO is supported| |null| diff --git a/docs/generators/dart.md b/docs/generators/dart.md index 42cb8b3bf58d..fbd5d7dd1d5c 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |pubAuthorEmail|Email address of the author in generated pubspec| |null| |pubDescription|Description in generated pubspec| |null| |pubHomepage|Homepage in generated pubspec| |null| +|pubLibrary|Library name in generated code| |null| |pubName|Name in generated pubspec| |null| |pubVersion|Version in generated pubspec| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 40d898959730..c2568d66259b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -59,6 +59,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class); + public static final String PUB_LIBRARY = "pubLibrary"; public static final String PUB_NAME = "pubName"; public static final String PUB_VERSION = "pubVersion"; public static final String PUB_DESCRIPTION = "pubDescription"; @@ -67,6 +68,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String PUB_HOMEPAGE = "pubHomepage"; public static final String USE_ENUM_EXTENSION = "useEnumExtension"; + protected String pubLibrary = "openapi.api"; protected String pubName = "openapi"; protected String pubVersion = "1.0.0"; protected String pubDescription = "OpenAPI API client"; @@ -169,6 +171,7 @@ public DartClientCodegen() { typeMapping.put("URI", "String"); typeMapping.put("ByteArray", "String"); + cliOptions.add(new CliOption(PUB_LIBRARY, "Library name in generated code")); cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec")); cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec")); @@ -214,6 +217,13 @@ public void processOpts() { 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 + additionalProperties.put(PUB_LIBRARY, pubLibrary); + } + if (additionalProperties.containsKey(PUB_VERSION)) { this.setPubVersion((String) additionalProperties.get(PUB_VERSION)); } else { @@ -409,7 +419,7 @@ public String toDefaultValue(Schema schema) { if (schema.getDefault() != null) { if (ModelUtils.isStringSchema(schema)) { - return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\""; + return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; } return schema.getDefault().toString(); } else { @@ -532,7 +542,7 @@ public String toEnumValue(String value, String datatype) { "int".equalsIgnoreCase(datatype)) { return value; } else { - return "\"" + escapeText(value) + "\""; + return "'" + escapeText(value) + "'"; } } @@ -548,6 +558,10 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } + public void setPubLibrary(String pubLibrary) { + this.pubLibrary = pubLibrary; + } + public void setPubName(String pubName) { this.pubName = pubName; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java index 4c6b02361048..cdcb958998a0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java @@ -130,7 +130,7 @@ public String toDefaultValue(Schema schema) { if (schema.getDefault() != null) { if (ModelUtils.isStringSchema(schema)) { - return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\""; + return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; } return schema.getDefault().toString(); } else { @@ -179,6 +179,13 @@ public void processOpts() { additionalProperties.put(IS_FORMAT_JSON, true); + if (additionalProperties.containsKey(PUB_LIBRARY)) { + this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY)); + } else { + //not set, use to be passed to template + additionalProperties.put(PUB_LIBRARY, pubLibrary); + } + if (additionalProperties.containsKey(PUB_NAME)) { this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java index 78e9f497a3cf..f4cc7dd1df32 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java @@ -140,7 +140,7 @@ public String toDefaultValue(Schema schema) { if (schema.getDefault() != null) { if (ModelUtils.isStringSchema(schema)) { - return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\""; + return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; } return schema.getDefault().toString(); } else { @@ -172,6 +172,13 @@ public void processOpts() { additionalProperties.put(IS_FORMAT_PROTO, false); } + if (additionalProperties.containsKey(PUB_LIBRARY)) { + this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY)); + } else { + //not set, use to be passed to template + additionalProperties.put(PUB_LIBRARY, pubLibrary); + } + if (additionalProperties.containsKey(PUB_NAME)) { this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index a16cba3d5fa2..161d22c66a76 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -1,18 +1,18 @@ -# {{pubName}} +# {{{pubName}}} {{#appDescriptionWithNewLines}} {{{appDescriptionWithNewLines}}} {{/appDescriptionWithNewLines}} This Dart package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: -- API version: {{appVersion}} +- API version: {{{appVersion}}} {{#artifactVersion}} -- Package version: {{artifactVersion}} +- Package version: {{{artifactVersion}}} {{/artifactVersion}} {{^hideGenerationTimestamp}} -- Build date: {{generatedDate}} +- Build date: {{{generatedDate}}} {{/hideGenerationTimestamp}} -- Build package: {{generatorClass}} +- Build package: {{{generatorClass}}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) {{/infoUrl}} @@ -27,16 +27,16 @@ Dart 2.0 or later If this Dart package is published to Github, add the following dependency to your pubspec.yaml ``` dependencies: - {{pubName}}: - git: https://{{gitHost}}/{{gitUserId}}/{{gitRepoId}}.git + {{{pubName}}}: + git: https://{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}.git ``` ### Local To use the package in your local drive, add the following dependency to your pubspec.yaml ``` dependencies: - {{pubName}}: - path: /path/to/{{pubName}} + {{{pubName}}}: + path: /path/to/{{{pubName}}} ``` ## Tests @@ -48,7 +48,7 @@ TODO Please follow the [installation procedure](#installation--usage) and then run the following: ```dart -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} {{#hasAuthMethods}} {{#authMethods}} @@ -80,34 +80,34 @@ import 'package:{{pubName}}/api.dart'; {{/authMethods}} {{/hasAuthMethods}} -var api_instance = {{classname}}(); +final api_instance = {{{classname}}}(); {{#allParams}} -var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +final {{{paramName}}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{dataType}}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}final result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#returnType}} print(result); {{/returnType}} } catch (e) { - print("Exception when calling {{classname}}->{{operationId}}: $e\n"); + print('Exception when calling {{{classname}}}->{{{operationId}}}: $e\n'); } {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` ## Documentation for API Endpoints -All URIs are relative to *{{basePath}}* +All URIs are relative to *{{{basePath}}}* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{{classname}}}* | [**{{{operationId}}}**]({{{apiDocPath}}}/{{{classname}}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} ## Documentation For Models -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md) +{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}/{{{classname}}}.md) {{/model}}{{/models}} ## Documentation For Authorization @@ -122,7 +122,7 @@ Class | Method | HTTP request | Description {{/isApiKey}} {{#isBasic}} {{#isBasicBasic}} -- **Type**: HTTP basicc authentication +- **Type**: HTTP Basic authentication {{/isBasicBasic}} {{#isBasicBearer}} - **Type**: HTTP Bearer authentication @@ -140,6 +140,6 @@ Class | Method | HTTP request | Description ## Author -{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{#apiInfo}}{{#apis}}{{^hasMore}}{{{infoEmail}}} {{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index ca638860499d..8bff5b93f832 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -1,117 +1,183 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} {{#operations}} +class {{{classname}}} { + {{{classname}}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; -class {{classname}} { final ApiClient apiClient; - - {{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; - {{#operation}} - /// {{summary}} with HTTP info returned - /// - /// {{notes}} - {{#returnType}}Future {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}WithHttpInfo({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { - Object postBody{{#bodyParam}} = {{paramName}}{{/bodyParam}}; - // verify required params are set + {{#summary}} + /// {{{summary}}} + {{/summary}} + {{#notes}} + {{#summary}} + /// + {{/summary}} + /// {{{notes}}} + /// + /// Note: This method returns the HTTP [Response]. + {{/notes}} + {{^notes}} + {{#summary}} + /// + /// Note: This method returns the HTTP [Response]. + {{/summary}} + {{^summary}} + /// Performs an HTTP '{{{httpMethod}}} {{{path}}}' operation and returns the [Response]. + {{/summary}} + {{/notes}} + {{#hasParams}} + {{#summary}} + /// + {{/summary}} + {{^summary}} + {{#notes}} + /// + {{/notes}} + {{/summary}} + /// Parameters: + /// + {{/hasParams}} + {{#allParams}} + /// * [{{{dataType}}}] {{{paramName}}}{{#required}} (required){{/required}}{{#optional}} (optional){{/optional}}: + {{#description}} + /// {{{description}}} + {{/description}} + {{#hasMore}} + /// + {{/hasMore}} + {{/allParams}} + {{#returnType}}Future {{/returnType}}{{^returnType}}Future {{/returnType}}{{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { + // Verify required params are set. {{#allParams}} {{#required}} - if({{paramName}} == null) { - throw ApiException(400, "Missing required param: {{paramName}}"); + if ({{{paramName}}} == null) { + throw ApiException(400, 'Missing required param: {{{paramName}}}'); } {{/required}} {{/allParams}} - // create path and map variables - String path = "{{{path}}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{baseName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; + final path = '{{{path}}}'.replaceAll('{format}', 'json'){{#pathParams}}.replaceAll('{' + '{{{baseName}}}' + '}', {{{paramName}}}.toString()){{/pathParams}}; + + Object postBody{{#bodyParam}} = {{{paramName}}}{{/bodyParam}}; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; {{#queryParams}} - {{^required}} - if({{paramName}} != null) { - {{/required}} - queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); - {{^required}} + {{^required}} + if ({{{paramName}}} != null) { + {{/required}} + queryParams.addAll(_convertParametersForCollectionFormat('{{{collectionFormat}}}', '{{{baseName}}}', {{{paramName}}})); + {{^required}} } - {{/required}} + {{/required}} {{/queryParams}} {{#headerParams}} - headerParams["{{baseName}}"] = {{paramName}}; + headerParams['{{{baseName}}}'] = {{{paramName}}}; {{/headerParams}} - List contentTypes = [{{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; + final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = [{{#authMethods}}'{{{name}}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = [{{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); {{#formParams}} {{^isFile}} - if ({{paramName}} != null) { + if ({{{paramName}}} != null) { hasFields = true; - mp.fields['{{baseName}}'] = parameterToString({{paramName}}); + mp.fields['{{{baseName}}}'] = parameterToString({{{paramName}}}); } {{/isFile}} {{#isFile}} - if ({{paramName}} != null) { + if ({{{paramName}}} != null) { hasFields = true; - mp.fields['{{baseName}}'] = {{paramName}}.field; - mp.files.add({{paramName}}); + mp.fields['{{{baseName}}}'] = {{{paramName}}}.field; + mp.files.add({{{paramName}}}); } {{/isFile}} {{/formParams}} - if(hasFields) + if (hasFields) { postBody = mp; - } - else { + } + } else { {{#formParams}} {{^isFile}} - if ({{paramName}} != null) - formParams['{{baseName}}'] = parameterToString({{paramName}}); + if ({{{paramName}}} != null) { + formParams['{{{baseName}}}'] = parameterToString({{{paramName}}}); + } {{/isFile}} {{/formParams}} } - var response = await apiClient.invokeAPI(path, - '{{httpMethod}}', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + '{{{httpMethod}}}', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } - /// {{summary}} + {{#summary}} + /// {{{summary}}} + {{/summary}} + {{#notes}} + {{#summary}} + /// + {{/summary}} + /// {{{notes}}} + {{/notes}} + {{#hasParams}} + {{#summary}} /// + {{/summary}} + {{^summary}} + {{#notes}} + /// + {{/notes}} + {{/summary}} + /// Parameters: + /// + {{/hasParams}} {{#allParams}} - ///{{dataType}} {{paramName}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: - /// {{#description}} {{{description}}}{{/description}} + /// * [{{{dataType}}}] {{{paramName}}}{{#required}} (required){{/required}}{{#optional}} (optional){{/optional}}: + {{#description}} + /// {{{description}}} + {{/description}} + {{#hasMore}} + /// + {{/hasMore}} {{/allParams}} - /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { - Response response = await {{nickname}}WithHttpInfo({{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}} {{#allParams}}{{^required}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} {{/hasOptionalParams}}); - if(response.statusCode >= 400) { + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{{nickname}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { + final response = await {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}} {{#allParams}}{{^required}}{{{paramName}}}: {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} {{/hasOptionalParams}}); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { {{#isListContainer}} {{#returnType}} - return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List).map((item) => item as {{returnBaseType}}).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List) + .map((item) => item as {{{returnBaseType}}}) + .toList(growable: false); {{/returnType}} {{/isListContainer}} {{^isListContainer}} {{#isMapContainer}} {{#returnType}} return {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}')); - {{/returnType}}; + {{/returnType}} {{/isMapContainer}} {{^isMapContainer}} {{#returnType}} @@ -119,11 +185,9 @@ class {{classname}} { {{/returnType}} {{/isMapContainer}} {{/isListContainer}} - } else { - return{{#returnType}} null{{/returnType}}; } + return{{#returnType}} null{{/returnType}}; } - {{/operation}} } {{/operations}} 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 a933252c0de6..340978123e73 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -1,182 +1,205 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} class QueryParam { + QueryParam(this.name, this.value); + String name; String value; - - QueryParam(this.name, this.value); } class ApiClient { - - String basePath; - var client = Client(); - - Map _defaultHeaderMap = {}; - Map _authentications = {}; - - final _regList = RegExp(r'^List<(.*)>$'); - final _regMap = RegExp(r'^Map$'); - - ApiClient({this.basePath = "{{{basePath}}}"}) { + ApiClient({this.basePath = '{{{basePath}}}'}) { {{#hasAuthMethods}} // Setup authentications (key: authentication name, value: authentication). {{#authMethods}} {{#isBasic}} {{#isBasicBasic}} - _authentications['{{name}}'] = HttpBasicAuth(); + _authentications['{{{name}}}'] = HttpBasicAuth(); {{/isBasicBasic}} {{#isBasicBearer}} - _authentications['{{name}}'] = HttpBearerAuth(); + _authentications['{{{name}}}'] = HttpBearerAuth(); {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} - _authentications['{{name}}'] = ApiKeyAuth({{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}{{^isKeyInCookie}}{{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}{{/isKeyInCookie}}, "{{keyParamName}}"); + _authentications['{{{name}}}'] = ApiKeyAuth({{#isKeyInCookie}}'cookie'{{/isKeyInCookie}}{{^isKeyInCookie}}{{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{^isKeyInHeader}}'query'{{/isKeyInHeader}}{{/isKeyInCookie}}, '{{{keyParamName}}}'); {{/isApiKey}} {{#isOAuth}} - _authentications['{{name}}'] = OAuth(); + _authentications['{{{name}}}'] = OAuth(); {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} } - void addDefaultHeader(String key, String value) { - _defaultHeaderMap[key] = value; - } + final String basePath; - dynamic _deserialize(dynamic value, String targetType) { - try { - switch (targetType) { - case 'String': - return '$value'; - case 'int': - return value is int ? value : int.parse('$value'); - case 'bool': - return value is bool ? value : '$value'.toLowerCase() == 'true'; - case 'double': - return value is double ? value : double.parse('$value'); - {{#models}} - {{#model}} - case '{{classname}}': - {{#isEnum}} - return new {{classname}}TypeTransformer().decode(value); - {{/isEnum}} - {{^isEnum}} - return {{classname}}.fromJson(value); - {{/isEnum}} - {{/model}} - {{/models}} - default: - { - Match match; - if (value is List && - (match = _regList.firstMatch(targetType)) != null) { - var newTargetType = match[1]; - return value.map((v) => _deserialize(v, newTargetType)).toList(); - } else if (value is Map && - (match = _regMap.firstMatch(targetType)) != null) { - var newTargetType = match[1]; - return Map.fromIterables(value.keys, - value.values.map((v) => _deserialize(v, newTargetType))); - } - } - } - } on Exception catch (e, stack) { - throw ApiException.withInner(500, 'Exception during deserialization.', e, stack); + var _client = Client(); + + /// Returns the current HTTP [Client] instance to use in this class. + /// + /// The return value is guaranteed to never be null. + Client get client => _client; + + /// Requests to use a new HTTP [Client] in this class. + /// + /// If the [newClient] is null, an [ArgumentError] is thrown. + set client(Client newClient) { + if (newClient == null) { + throw ArgumentError('New client instance cannot be null.'); } - throw ApiException(500, 'Could not find a suitable class for deserialization'); + _client = newClient; } - dynamic deserialize(String json, String targetType) { + final _defaultHeaderMap = {}; + final _authentications = {}; + + void addDefaultHeader(String key, String value) { + _defaultHeaderMap[key] = value; + } + + dynamic deserialize(String json, String targetType, {bool growable}) { // Remove all spaces. Necessary for reg expressions as well. targetType = targetType.replaceAll(' ', ''); - if (targetType == 'String') return json; - - var decodedJson = jsonDecode(json); - return _deserialize(decodedJson, targetType); + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: true == growable); } - String serialize(Object obj) { - String serialized = ''; - if (obj == null) { - serialized = ''; - } else { - serialized = json.encode(obj); - } - return serialized; - } + String serialize(Object obj) => obj == null ? '' : json.encode(obj); - // We don't use a Map for queryParams. - // If collectionFormat is 'multi' a key might appear multiple times. - Future invokeAPI(String path, - String method, - Iterable queryParams, - Object body, - Map headerParams, - Map formParams, - String nullableContentType, - List authNames) async { + T getAuthentication(String name) { + final authentication = _authentications[name]; + return authentication is T ? authentication : null; + } + // We don’t use a Map for queryParams. + // If collectionFormat is 'multi', a key might appear multiple times. + Future invokeAPI( + String path, + String method, + Iterable queryParams, + Object body, + Map headerParams, + Map formParams, + String nullableContentType, + List authNames, + ) async { _updateParamsForAuth(authNames, queryParams, headerParams); - var ps = queryParams + headerParams.addAll(_defaultHeaderMap); + + final ps = queryParams .where((p) => p.value != null) .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); - String queryString = ps.isNotEmpty ? - '?' + ps.join('&') : - ''; + final queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; - String url = basePath + path + queryString; + final url = '$basePath$path$queryString'; - headerParams.addAll(_defaultHeaderMap); if (nullableContentType != null) { - final contentType = nullableContentType; - headerParams['Content-Type'] = contentType; + headerParams['Content-Type'] = nullableContentType; } - if(body is MultipartRequest) { - var request = MultipartRequest(method, Uri.parse(url)); + if (body is MultipartRequest) { + final request = MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - var response = await client.send(request); + final response = await _client.send(request); return Response.fromStream(response); - } else { - var msgBody = nullableContentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); - final nullableHeaderParams = (headerParams.isEmpty)? null: headerParams; + } + + final msgBody = nullableContentType == 'application/x-www-form-urlencoded' + ? formParams + : serialize(body); + final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; + + try { switch(method) { - case "POST": - return client.post(url, headers: nullableHeaderParams, body: msgBody); - case "PUT": - return client.put(url, headers: nullableHeaderParams, body: msgBody); - case "DELETE": - return client.delete(url, headers: nullableHeaderParams); - case "PATCH": - return client.patch(url, headers: nullableHeaderParams, body: msgBody); - case "HEAD": - return client.head(url, headers: nullableHeaderParams); + case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody); + case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody); + case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams); + case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody); + case 'HEAD': return await _client.head(url, headers: nullableHeaderParams); + case 'GET': return await _client.get(url, headers: nullableHeaderParams); + } + } on SocketException catch (e, trace) { + throw ApiException.withInner(400, 'Socket operation failed: $method $path', e, trace); + } on TlsException catch (e, trace) { + throw ApiException.withInner(400, 'TLS/SSL communication failed: $method $path', e, trace); + } on IOException catch (e, trace) { + throw ApiException.withInner(400, 'I/O operation failed: $method $path', e, trace); + } on Exception catch (e, trace) { + throw ApiException.withInner(400, 'Exception occurred: $method $path', e, trace); + } + + throw ApiException(400, 'Invalid HTTP operation: $method $path'); + } + + dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + try { + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + if (value is bool) { + return value; + } + final valueString = '$value'.toLowerCase(); + return valueString == 'true' || valueString == '1'; + break; + case 'double': + return value is double ? value : double.parse('$value'); + {{#models}} + {{#model}} + case '{{{classname}}}': + {{#isEnum}} + return {{{classname}}}TypeTransformer().decode(value); + {{/isEnum}} + {{^isEnum}} + return {{{classname}}}.fromJson(value); + {{/isEnum}} + {{/model}} + {{/models}} default: - return client.get(url, headers: nullableHeaderParams); + Match match; + if (value is List && (match = _regList.firstMatch(targetType)) != null) { + final newTargetType = match[1]; + return value + .map((v) => _deserialize(v, newTargetType, growable: growable)) + .toList(growable: true == growable); + } + if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { + final newTargetType = match[1]; + return Map.fromIterables( + value.keys, + value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + ); + } + break; } + } on Exception catch (e, stack) { + throw ApiException.withInner(500, 'Exception during deserialization.', e, stack); } + throw ApiException(500, 'Could not find a suitable class for deserialization'); } /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { authNames.forEach((authName) { - Authentication auth = _authentications[authName]; - if (auth == null) throw ArgumentError("Authentication undefined: " + authName); + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } auth.applyToParams(queryParams, headerParams); }); } - - T getAuthentication(String name) { - var authentication = _authentications[name]; - - return authentication is T ? authentication : null; - } } 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 5e0192005d0b..32f034829cca 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -1,22 +1,22 @@ -# {{pubName}}.api.{{classname}}{{#description}} -{{description}}{{/description}} +# {{{pubName}}}.api.{{{classname}}}{{#description}} +{{{description}}}{{/description}} ## Load the API package ```dart -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; ``` -All URIs are relative to *{{basePath}}* +All URIs are relative to *{{{basePath}}}* Method | HTTP request | Description ------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}} {{#operations}} {{#operation}} # **{{{operationId}}}** -> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{{summary}}}{{#notes}} @@ -24,7 +24,7 @@ Method | HTTP request | Description ### Example ```dart -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} @@ -55,18 +55,18 @@ import 'package:{{pubName}}/api.dart'; {{/authMethods}} {{/hasAuthMethods}} -var api_instance = {{classname}}(); +final api_instance = {{{classname}}}(); {{#allParams}} -var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +final {{{paramName}}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{dataType}}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}final result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#returnType}} print(result); {{/returnType}} } catch (e) { - print("Exception when calling {{classname}}->{{operationId}}: $e\n"); + print('Exception when calling {{{classname}}}->{{{operationId}}}: $e\n'); } ``` @@ -74,12 +74,12 @@ try { {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#allParams}} **{{{paramName}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/allParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{{returnBaseType}}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} ### Authorization 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 5964f88f93d7..40f4fda731ee 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -1,23 +1,22 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} class ApiException implements Exception { + ApiException(this.code, this.message); + + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + int code = 0; String message; Exception innerException; StackTrace stackTrace; - ApiException(this.code, this.message); - - ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); - String toString() { - if (message == null) return "ApiException"; - + if (message == null) { + return 'ApiException'; + } if (innerException == null) { - return "ApiException $code: $message"; + return 'ApiException $code: $message'; } - - return "ApiException $code: $message (Inner exception: $innerException)\n\n" + - stackTrace.toString(); + return 'ApiException $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 1b1f309018d2..35300254aa19 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache @@ -1,65 +1,61 @@ -part of {{pubName}}.api; - -const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; -var _dateFormatter = DateFormat('yyyy-MM-dd'); - -// port from Java version +{{>header}} +{{>part_of}} +// Ported from the Java version. Iterable _convertParametersForCollectionFormat( - String collectionFormat, String name, dynamic value) { - var params = []; + String collectionFormat, + String name, + dynamic value, +) { + final params = []; // preconditions - if (name == null || name.isEmpty || value == null) return params; - - if (value is! List) { - params.add(QueryParam(name, parameterToString(value))); - return params; - } - - List values = value as List; - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" - : collectionFormat; // default: csv - - if (collectionFormat == "multi") { - return values.map((v) => QueryParam(name, parameterToString(v))); + if (name != null && !name.isEmpty && value != null) { + if (value is List) { + // get the collection format, default: csv + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? 'csv' + : collectionFormat; + + if (collectionFormat == 'multi') { + return value.map((v) => QueryParam(name, parameterToString(v))); + } + + final delimiter = _delimiters[collectionFormat] ?? ','; + + params.add(QueryParam(name, value.map((v) => parameterToString(v)).join(delimiter))); + } else { + params.add(QueryParam(name, parameterToString(value))); + } } - String delimiter = _delimiters[collectionFormat] ?? ","; - - params.add(QueryParam(name, values.map((v) => parameterToString(v)).join(delimiter))); return params; } -/// Format the given parameter object into string. +/// Format the given parameter object into a [String]. String parameterToString(dynamic value) { if (value == null) { return ''; - } else if (value is DateTime) { + } + if (value is DateTime) { return value.toUtc().toIso8601String(); + } {{#models}} {{#model}} {{#isEnum}} - } else if (value is {{classname}}) { - return {{classname}}TypeTransformer().encode(value).toString(); + if (value is {{{classname}}}) { + return {{{classname}}}TypeTransformer().encode(value).toString(); + } {{/isEnum}} {{/model}} {{/models}} - } else { - return value.toString(); - } + return value.toString(); } -/// Returns the decoded body by utf-8 if application/json with the given headers. -/// Else, returns the decoded body by default algorithm of dart:http. -/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +/// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json' +/// content type. Otherwise, returns the decoded body as decoded by dart:http package. String _decodeBodyBytes(Response response) { - var contentType = response.headers['content-type']; - if (contentType != null && contentType.contains("application/json")) { - return utf8.decode(response.bodyBytes); - } else { - return response.body; - } + final contentType = response.headers['content-type']; + return contentType != null && contentType.contains('application/json') + ? utf8.decode(response.bodyBytes) + : response.body; } diff --git a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache index 07459b09938b..3d783bf62d86 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache @@ -1,13 +1,14 @@ -import 'package:{{pubName}}/api.dart'; +{{>header}} +import 'package:{{{pubName}}}/api.dart'; import 'package:test/test.dart'; {{#operations}} -/// tests for {{classname}} +/// tests for {{{classname}}} void main() { - var instance = {{classname}}(); + final instance = {{{classname}}}(); - group('tests for {{classname}}', () { + group('tests for {{{classname}}}', () { {{#operation}} {{#summary}} // {{{.}}} @@ -17,8 +18,8 @@ void main() { // {{{.}}} // {{/notes}} - //{{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{operationId}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async - test('test {{operationId}}', () async { + //{{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async + test('test {{{operationId}}}', () async { // TODO }); diff --git a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache index 00bdc4285511..7502f877acdd 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -1,7 +1,10 @@ -library {{pubName}}.api; +{{>header}} +{{#pubLibrary}}library {{{pubLibrary}}};{{/pubLibrary}}{{^pubLibrary}}library {{{pubName}}}.api;{{/pubLibrary}} import 'dart:async'; import 'dart:convert'; +import 'dart:io'; + import 'package:http/http.dart'; import 'package:intl/intl.dart'; import 'package:meta/meta.dart'; @@ -15,9 +18,14 @@ part 'auth/oauth.dart'; part 'auth/http_basic_auth.dart'; part 'auth/http_bearer_auth.dart'; -{{#apiInfo}}{{#apis}}part 'api/{{classFilename}}.dart'; +{{#apiInfo}}{{#apis}}part 'api/{{{classFilename}}}.dart'; {{/apis}}{{/apiInfo}} -{{#models}}{{#model}}part 'model/{{classFilename}}.dart'; +{{#models}}{{#model}}part 'model/{{{classFilename}}}.dart'; {{/model}}{{/models}} +const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; +const _dateEpochMarker = 'epoch'; +final _dateFormatter = DateFormat('yyyy-MM-dd'); +final _regList = RegExp(r'^List<(.*)>$'); +final _regMap = RegExp(r'^Map$'); ApiClient defaultApiClient = ApiClient(); 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 e429cd61dda2..b3aa05f2f68e 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,24 +1,17 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} class ApiKeyAuth implements Authentication { + ApiKeyAuth(this.location, this.paramName); final String location; final String paramName; - String _apiKey; - String apiKeyPrefix; - - set apiKey(String key) => _apiKey = key; - ApiKeyAuth(this.location, this.paramName); + String apiKeyPrefix; + String apiKey; @override void applyToParams(List queryParams, Map headerParams) { - String value; - if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $_apiKey'; - } else { - value = _apiKey; - } + final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; if (location == 'query' && value != null) { queryParams.add(QueryParam(paramName, value)); @@ -26,7 +19,7 @@ class ApiKeyAuth implements Authentication { headerParams[paramName] = value; } else if (location == 'cookie' && value != null) { headerParams.update('Cookie', (String existingCookie) { - return "$existingCookie; $paramName=$value"; + return '$existingCookie; $paramName=$value'; }, ifAbsent: () => '$paramName=$value'); } } 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 00bbbf09746d..ec754159c2d6 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,6 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} abstract class Authentication { - - /// Apply authentication settings to header and query params. - void applyToParams(List queryParams, Map headerParams); + /// Apply authentication settings to header and query params. + void applyToParams(List queryParams, Map headerParams); } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache new file mode 100644 index 000000000000..db48248792a9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache @@ -0,0 +1,8 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars 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 efbbcfb30353..8be1da065a08 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,16 +1,12 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} class HttpBasicAuth implements Authentication { - - String _username; - String _password; + String username; + String password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); - headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); + final credentials = (username ?? '') + ':' + (password ?? ''); + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; } - - set username(String username) => _username = username; - set password(String password) => _password = password; } 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 7390098fc48a..21469bdb0881 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,25 +1,29 @@ -part of {{pubName}}.api; +{{>header}} +{{>part_of}} +typedef HttpBearerAuthProvider = String Function(); class HttpBearerAuth implements Authentication { + HttpBearerAuth(); + dynamic _accessToken; - HttpBearerAuth() { } + dynamic get accessToken => _accessToken; + + set accessToken(dynamic accessToken) { + if (accessToken is! String && accessToken is! HttpBearerAuthProvider) { + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + } + this._accessToken = accessToken; + } @override void applyToParams(List queryParams, Map headerParams) { if (_accessToken is String) { - headerParams["Authorization"] = "Bearer " + _accessToken; - } else if (_accessToken is String Function()){ - headerParams["Authorization"] = "Bearer " + _accessToken(); + headerParams['Authorization'] = 'Bearer $_accessToken'; + } else if (_accessToken is HttpBearerAuthProvider) { + headerParams['Authorization'] = 'Bearer ${_accessToken()}'; } else { - throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } } - - void setAccessToken(dynamic accessToken) { - if (!((accessToken is String) | (accessToken is String Function()))){ - throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); - } - this._accessToken = accessToken; - } } 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 58695a8a3efc..6cdd30dceb27 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache @@ -1,16 +1,14 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} class OAuth implements Authentication { - String _accessToken; + OAuth({this.accessToken}); - OAuth({String accessToken}) : _accessToken = accessToken; + String accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (_accessToken != null) { - headerParams["Authorization"] = "Bearer $_accessToken"; + if (accessToken != null) { + headerParams['Authorization'] = 'Bearer $accessToken'; } } - - set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/part_of.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/part_of.mustache new file mode 100644 index 000000000000..d9f1d409755c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/auth/part_of.mustache @@ -0,0 +1 @@ +{{#pubLibrary}}part of {{{pubLibrary}}};{{/pubLibrary}}{{^pubLibrary}}part of {{{pubName}}}.api;{{/pubLibrary}} diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index f7b5ca697b50..84380954d8fa 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -1,105 +1,112 @@ -class {{classname}} { +class {{{classname}}} { + /// Returns a new [{{{classname}}}] instance. + {{{classname}}}({ {{#vars}} - {{#description}}/// {{{description}}}{{/description}} - {{^isEnum}} - {{^defaultValue}}{{{dataType}}} {{name}};{{/defaultValue}}{{#defaultValue}}{{{dataType}}} {{name}} = {{defaultValue}};{{/defaultValue}} - {{/isEnum}} - {{#isEnum}} - {{#allowableValues}} - {{#min}} // range from {{min}} to {{max}}{{/min}}{{classname}}{{{enumName}}} {{name}}{{#required}} = {{classname}}{{{enumName}}}._internal({{{defaultValue}}}){{/required}}{{^required}}{{/required}}; - {{/allowableValues}} - {{/isEnum}} - {{/vars}} - - {{classname}}({ - {{#vars}} - {{#required}}@required this.{{name}}{{/required}}{{^required}}this.{{name}}{{#defaultValue}} = {{defaultValue}}{{/defaultValue}}{{/required}}, + {{#isNullable}}{{#required}}@required {{/required}}this.{{{name}}},{{/isNullable}}{{^isNullable}}{{#defaultValue}}this.{{{name}}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{#required}}@required {{/required}}this.{{{name}}}{{/defaultValue}},{{/isNullable}} {{/vars}} }); - @override - String toString() { - return '{{classname}}[{{#vars}}{{name}}=${{name}}, {{/vars}}]'; - } - - {{classname}}.fromJson(Map json) { - if (json == null) return; + /// Returns a new [{{{classname}}}] instance and optionally import its values from + /// [json] if it's non-null. + {{{classname}}}.fromJson(Map json) { + if (json != null) { {{#vars}} {{#isDateTime}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - DateTime.parse(json['{{baseName}}']); + {{{name}}} = json['{{{baseName}}}'] == null + ? null + {{#pattern}} + : _dateEpochMarker == '{{{pattern}}}' + ? DateTime.fromMillisecondsSinceEpoch(json['{{{baseName}}}'] as int, isUtc: true) + : DateTime.parse(json['{{{baseName}}}']); + {{/pattern}} + {{^pattern}} + : DateTime.parse(json['{{{baseName}}}']); + {{/pattern}} {{/isDateTime}} {{#isDate}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - DateTime.parse(json['{{baseName}}']); + {{{name}}} = json['{{{baseName}}}'] == null + ? null + {{#pattern}} + : _dateEpochMarker == '{{{pattern}}}' + ? DateTime.fromMillisecondsSinceEpoch(json['{{{baseName}}}'] as int, isUtc: true) + : DateTime.parse(json['{{{baseName}}}']); + {{/pattern}} + {{^pattern}} + : DateTime.parse(json['{{{baseName}}}']); + {{/pattern}} {{/isDate}} {{^isDateTime}} {{^isDate}} {{#complexType}} {{#isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{#items.isListContainer}} - (json['{{baseName}}'] as List).map( - (e) => e == null ? null : + {{#items.isListContainer}} + {{{name}}} = json['{{{baseName}}}'] == null + ? null + : (json['{{{baseName}}}'] as List).map( {{#items.complexType}} - {{items.complexType}}.listFromJson(json['{{baseName}}']) + {{items.complexType}}.listFromJson(json['{{{baseName}}}']) {{/items.complexType}} {{^items.complexType}} - (e as List).cast<{{items.items.dataType}}>() + (e) => e == null ? null : (e as List).cast<{{items.items.dataType}}>() {{/items.complexType}} - ).toList(); - {{/items.isListContainer}} - {{^items.isListContainer}} - {{complexType}}.listFromJson(json['{{baseName}}']); - {{/items.isListContainer}} + ).toList(growable: false); + {{/items.isListContainer}} + {{^items.isListContainer}} + {{{name}}} = {{{complexType}}}.listFromJson(json['{{{baseName}}}']); + {{/items.isListContainer}} {{/isListContainer}} {{^isListContainer}} - {{#isMapContainer}} - {{#items.isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{items.complexType}}.mapListFromJson(json['{{baseName}}']); - {{/items.isListContainer}} - {{^items.isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{complexType}}.mapFromJson(json['{{baseName}}']); - {{/items.isListContainer}} - {{/isMapContainer}} - {{^isMapContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{complexType}}.fromJson(json['{{baseName}}']); - {{/isMapContainer}} + {{#isMapContainer}} + {{#items.isListContainer}} + {{{name}}} = json['{{{baseName}}}'] == null + ? null + {{#items.complexType}} + : {{items.complexType}}.mapListFromJson(json['{{{baseName}}}']); + {{/items.complexType}} + {{^items.complexType}} + : (json['{{{baseName}}}'] as Map).cast(); + {{/items.complexType}} + {{/items.isListContainer}} + {{^items.isListContainer}} + {{{name}}} = json['{{{baseName}}}'] == null + ? null + : {{{complexType}}}.mapFromJson(json['{{{baseName}}}']); + {{/items.isListContainer}} + {{/isMapContainer}} + {{^isMapContainer}} + {{{name}}} = {{{complexType}}}.fromJson(json['{{{baseName}}}']); + {{/isMapContainer}} {{/isListContainer}} {{/complexType}} {{^complexType}} {{#isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - (json['{{baseName}}'] as List).cast<{{items.datatype}}>(); + {{#isEnum}} + {{{name}}} = {{{classname}}}{{{items.datatypeWithEnum}}}.listFromJson(json['{{{baseName}}}']); + {{/isEnum}} + {{^isEnum}} + {{{name}}} = json['{{{baseName}}}'] == null + ? null + : (json['{{{baseName}}}'] as List).cast<{{{items.datatype}}}>(); + {{/isEnum}} {{/isListContainer}} {{^isListContainer}} {{#isMapContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - (json['{{baseName}}'] as Map).cast(); + {{{name}}} = json['{{{baseName}}}'] == null ? + null : + (json['{{{baseName}}}'] as Map).cast(); {{/isMapContainer}} {{^isMapContainer}} {{#isNumber}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - json['{{baseName}}'].toDouble(); + {{{name}}} = json['{{{baseName}}}'] == null ? + null : + json['{{{baseName}}}'].toDouble(); {{/isNumber}} {{^isNumber}} {{^isEnum}} - {{name}} = json['{{baseName}}']; + {{{name}}} = json['{{{baseName}}}']; {{/isEnum}} {{#isEnum}} - {{name}} = {{classname}}{{{enumName}}}.fromJson(json['{{baseName}}']); + {{{name}}} = {{{classname}}}{{{enumName}}}.fromJson(json['{{{baseName}}}']); {{/isEnum}} {{/isNumber}} {{/isMapContainer}} @@ -108,52 +115,99 @@ class {{classname}} { {{/isDate}} {{/isDateTime}} {{/vars}} + } } + {{#vars}} + {{#description}}/// {{{description}}}{{/description}} + {{^isEnum}} + {{{dataType}}} {{{name}}}; + {{/isEnum}} + {{#isEnum}} + {{#isContainer}} + {{#isListContainer}} + List<{{{classname}}}{{{enumName}}}> {{{name}}}; + {{/isListContainer}} + {{#isMapContainer}} + Map {{{name}}}; + {{/isMapContainer}} + {{/isContainer}} + {{^isContainer}} + {{#allowableValues}} + {{#min}} // range from {{{min}}} to {{{max}}}{{/min}}{{{classname}}}{{{enumName}}} {{{name}}}{{#required}} = {{{classname}}}{{{enumName}}}._({{{defaultValue}}}){{/required}}{{^required}}{{/required}}; + {{/allowableValues}} + {{/isContainer}} + {{/isEnum}} + + {{/vars}} + @override + bool operator ==(Object other) => identical(this, other) || other is {{{classname}}} && + {{#vars}} + other.{{{name}}} == {{{name}}}{{^-last}} &&{{/-last}}{{#-last}};{{/-last}} + {{/vars}} + + @override + int get hashCode => + {{#vars}} + {{#isNullable}}({{{name}}}?.hashCode ?? 0){{/isNullable}}{{^isNullable}}{{{name}}}.hashCode{{/isNullable}}{{^-last}} +{{/-last}}{{#-last}};{{/-last}} + {{/vars}} + + @override + String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; + Map toJson() { - Map json = {}; - {{#vars}} - {{^isNullable}} - if ({{name}} != null) - {{/isNullable}} - {{#isDateTime}} - json['{{baseName}}'] = {{name}} == null ? null : {{name}}.toUtc().toIso8601String(); - {{/isDateTime}} - {{#isDate}} - json['{{baseName}}'] = {{name}} == null ? null : _dateFormatter.format({{name}}.toUtc()); - {{/isDate}} - {{^isDateTime}} - {{^isDate}} - {{^isEnum}} - json['{{baseName}}'] = {{name}}; - {{/isEnum}} - {{#isEnum}} - json['{{baseName}}'] = {{name}}.value; - {{/isEnum}} - {{/isDate}} - {{/isDateTime}} - {{/vars}} + final json = {}; +{{#vars}} + if ({{{name}}} != null) { + {{#isDateTime}} + {{#pattern}} + json['{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? {{{name}}}.millisecondsSinceEpoch + : {{{name}}}.toUtc().toIso8601String(); + {{/pattern}} + {{^pattern}} + json['{{{baseName}}}'] = {{{name}}}.toUtc().toIso8601String(); + {{/pattern}} + {{/isDateTime}} + {{#isDate}} + {{#pattern}} + json['{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? {{{name}}}.millisecondsSinceEpoch + : _dateFormatter.format({{{name}}}.toUtc()); + {{/pattern}} + {{^pattern}} + json['{{{baseName}}}'] = _dateFormatter.format({{{name}}}.toUtc()); + {{/pattern}} + {{/isDate}} + {{^isDateTime}} + {{^isDate}} + json['{{{baseName}}}'] = {{{name}}}; + {{/isDate}} + {{/isDateTime}} + } +{{/vars}} return json; } - static List<{{classname}}> listFromJson(List json) { - return json == null ? List<{{classname}}>() : json.map((value) => {{classname}}.fromJson(value)).toList(); - } + static List<{{{classname}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : <{{{classname}}}>[] + : json.map((v) => {{{classname}}}.fromJson(v)).toList(growable: true == growable); - static Map mapFromJson(Map json) { - final map = Map(); + static Map mapFromJson(Map json) { + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = {{classname}}.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = {{{classname}}}.fromJson(v)); } return map; } - // maps a json object with a list of {{classname}}-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + // maps a json object with a list of {{{classname}}}-objects as value to a dart map + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = {{classname}}.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = {{{classname}}}.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; @@ -161,6 +215,7 @@ class {{classname}} { } {{#vars}} {{#isEnum}} + {{>enum_inline}} {{/isEnum}} {{/vars}} diff --git a/modules/openapi-generator/src/main/resources/dart2/enum.mustache b/modules/openapi-generator/src/main/resources/dart2/enum.mustache index cfda923660f9..683e0d8528cc 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum.mustache @@ -1,60 +1,87 @@ -class {{classname}} { +{{#description}}/// {{{description}}}{{/description}} +class {{{classname}}} { + /// Instantiate a new enum with the provided [value]. + const {{{classname}}}._(this.value); + /// The underlying value of this enum member. - final {{dataType}} value; + {{#isEnum}} + final String value; + {{/isEnum}} + {{^isEnum}} + final {{{dataType}}} value; + {{/isEnum}} + + @override + bool operator ==(Object other) => identical(this, other) || + other is {{{classname}}} && other.value == value || + other is {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} && other == value; - const {{classname}}._internal(this.value); + @override + int get hashCode => toString().hashCode; + + @override + String toString() => {{#isString}}value{{/isString}}{{^isString}}value.toString(){{/isString}}; + + {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} toJson() => value; {{#allowableValues}} {{#enumVars}} - {{#description}} - /// {{description}} - {{/description}} - static const {{classname}} {{{name}}} = {{classname}}._internal({{value}}); + static const {{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}} = {{{classname}}}._({{{value}}}); {{/enumVars}} {{/allowableValues}} - static List<{{classname}}> get values => const [ - {{#allowableValues}} - {{#enumVars}} - {{{name}}}, - {{/enumVars}} - {{/allowableValues}} - ]; - - {{dataType}} toJson () { - return value; - } - - @override - String toString () { - return value; - } + /// List of all possible values in this [enum][{{{classname}}}]. + static const values = <{{{classname}}}>[ + {{#allowableValues}} + {{#enumVars}} + {{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}}, + {{/enumVars}} + {{/allowableValues}} + ]; - static {{classname}} fromJson({{dataType}} value) { - return {{classname}}TypeTransformer().decode(value); - } + static {{{classname}}} fromJson({{{dataType}}} value) => + {{{classname}}}TypeTransformer().decode(value); - static List<{{classname}}> listFromJson(List json) { - return json == null - ? List<{{classname}}>() - : json.map((value) => {{classname}}.fromJson(value)).toList(); - } + static List<{{{classname}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : <{{{classname}}}>[] + : json + .map((value) => {{{classname}}}.fromJson(value)) + .toList(growable: true == growable); } -class {{classname}}TypeTransformer { +/// Transformation class that can [encode] an instance of [{{{classname}}}] to {{{dataType}}}, +/// and [decode] dynamic data back to [{{{classname}}}]. +class {{{classname}}}TypeTransformer { + const {{{classname}}}TypeTransformer._(); - dynamic encode({{classname}} data) { - return data.value; - } + factory {{{classname}}}TypeTransformer() => _instance ??= {{{classname}}}TypeTransformer._(); + + {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} encode({{{classname}}} data) => data.value; - {{classname}} decode(dynamic data) { + /// Decodes a [dynamic value][data] to a {{{classname}}}. + /// + /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, + /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] + /// cannot be decoded successfully, then an [UnimplementedError] is thrown. + /// + /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, + /// and users are still using an old app with the old code. + {{{classname}}} decode(dynamic data, {bool allowNull}) { switch (data) { {{#allowableValues}} {{#enumVars}} - case {{{value}}}: return {{classname}}.{{{name}}}; + case {{{value}}}: return {{{classname}}}.{{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}}; {{/enumVars}} {{/allowableValues}} - default: throw('Unknown enum value to decode: $data'); + default: + if (allowNull == false) { + throw ArgumentError('Unknown enum value to decode: $data'); + } } + return null; } -} + + /// Singleton [{{{classname}}}TypeTransformer] instance. + static {{{classname}}}TypeTransformer _instance; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache index dc334dface51..44ab77cceb5c 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache @@ -1,60 +1,87 @@ -class {{classname}}{{enumName}} { +{{#description}}/// {{{description}}}{{/description}} +class {{{classname}}}{{{enumName}}} { + /// Instantiate a new enum with the provided [value]. + const {{{classname}}}{{{enumName}}}._(this.value); + /// The underlying value of this enum member. + {{#isEnum}} + final String value; + {{/isEnum}} + {{^isEnum}} final {{{dataType}}} value; + {{/isEnum}} - const {{classname}}{{enumName}}._internal(this.value); + @override + bool operator ==(Object other) => identical(this, other) || + other is {{{classname}}}{{{enumName}}} && other.value == value || + other is {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} && other == value; - {{#allowableValues}} - {{#enumVars}} - {{#description}} - /// {{description}} - {{/description}} - static const {{classname}}{{enumName}} {{name}} = {{classname}}{{enumName}}._internal({{{value}}}); - {{/enumVars}} - {{/allowableValues}} + @override + int get hashCode => toString().hashCode; - static List<{{classname}}{{enumName}}> get values => const [ - {{#allowableValues}} - {{#enumVars}} - {{{name}}}, - {{/enumVars}} - {{/allowableValues}} - ]; + @override + String toString() => {{#isString}}value{{/isString}}{{^isString}}value.toString(){{/isString}}; - {{{dataType}}} toJson () { - return value; - } + {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} toJson() => value; - @override - String toString () { - return value; - } + {{#allowableValues}} + {{#enumVars}} + static const {{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}} = {{{classname}}}{{{enumName}}}._({{{value}}}); + {{/enumVars}} + {{/allowableValues}} - static {{classname}}{{enumName}} fromJson({{{dataType}}} value) { - return {{classname}}{{enumName}}TypeTransformer().decode(value); - } + /// List of all possible values in this [enum][{{{classname}}}{{{enumName}}}]. + static const values = <{{{classname}}}{{{enumName}}}>[ + {{#allowableValues}} + {{#enumVars}} + {{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}}, + {{/enumVars}} + {{/allowableValues}} + ]; - static List<{{classname}}{{enumName}}> listFromJson(List json) { - return json == null - ? List<{{classname}}{{enumName}}>() - : json.map((value) => {{classname}}{{enumName}}.fromJson(value)).toList(); - } + static {{{classname}}}{{{enumName}}} fromJson({{{dataType}}} value) => + {{{classname}}}{{{enumName}}}TypeTransformer().decode(value); + + static List<{{{classname}}}{{{enumName}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : <{{{classname}}}{{{enumName}}}>[] + : json + .map((value) => {{{classname}}}{{{enumName}}}.fromJson(value)) + .toList(growable: true == growable); } -class {{classname}}{{enumName}}TypeTransformer { +/// Transformation class that can [encode] an instance of [{{{classname}}}{{{enumName}}}] to {{{dataType}}}, +/// and [decode] dynamic data back to [{{{classname}}}{{{enumName}}}]. +class {{{classname}}}{{{enumName}}}TypeTransformer { + const {{{classname}}}{{{enumName}}}TypeTransformer._(); - dynamic encode({{classname}}{{enumName}} data) { - return data.value; - } + factory {{{classname}}}{{{enumName}}}TypeTransformer() => _instance ??= {{{classname}}}{{{enumName}}}TypeTransformer._(); + + {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} encode({{{classname}}}{{{enumName}}} data) => data.value; - {{classname}}{{enumName}} decode(dynamic data) { + /// Decodes a [dynamic value][data] to a {{{classname}}}{{{enumName}}}. + /// + /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, + /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] + /// cannot be decoded successfully, then an [UnimplementedError] is thrown. + /// + /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, + /// and users are still using an old app with the old code. + {{{classname}}}{{{enumName}}} decode(dynamic data, {bool allowNull}) { switch (data) { - {{#allowableValues}} - {{#enumVars}} - case {{{value}}}: return {{classname}}{{enumName}}.{{{name}}}; - {{/enumVars}} - {{/allowableValues}} - default: return null; + {{#allowableValues}} + {{#enumVars}} + case {{{value}}}: return {{{classname}}}{{{enumName}}}.{{#lambda.lowercase}}{{{name}}}{{/lambda.lowercase}}; + {{/enumVars}} + {{/allowableValues}} + default: + if (allowNull == false) { + throw ArgumentError('Unknown enum value to decode: $data'); + } } + return null; } -} + + /// Singleton [{{{classname}}}{{{enumName}}}TypeTransformer] instance. + static {{{classname}}}{{{enumName}}}TypeTransformer _instance; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart2/header.mustache b/modules/openapi-generator/src/main/resources/dart2/header.mustache new file mode 100644 index 000000000000..db48248792a9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/header.mustache @@ -0,0 +1,8 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars diff --git a/modules/openapi-generator/src/main/resources/dart2/model.mustache b/modules/openapi-generator/src/main/resources/dart2/model.mustache index 37b030ab0349..4bebe06e9e44 100644 --- a/modules/openapi-generator/src/main/resources/dart2/model.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/model.mustache @@ -1,5 +1,5 @@ -part of {{pubName}}.api; - +{{>header}} +{{>part_of}} {{#models}} {{#model}} {{#isEnum}} diff --git a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache index 6e9402d4473c..3537d6085d6b 100644 --- a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache @@ -1,21 +1,21 @@ {{#models}} {{#model}} -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; import 'package:test/test.dart'; -// tests for {{classname}} +// tests for {{{classname}}} void main() { - {{^isEnum}} - var instance = new {{classname}}(); - {{/isEnum}} + {{^isEnum}} + final instance = {{{classname}}}(); + {{/isEnum}} - group('test {{classname}}', () { + group('test {{{classname}}}', () { {{#vars}} {{#description}} // {{{description}}} {{/description}} - // {{{dataType}}} {{name}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} - test('to test the property `{{name}}`', () async { + // {{{dataType}}} {{{name}}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} + test('to test the property `{{{name}}}`', () async { // TODO }); diff --git a/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache index 742952fef632..94402b858e0d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache @@ -1,14 +1,14 @@ -{{#models}}{{#model}}# {{pubName}}.model.{{classname}} +{{#models}}{{#model}}# {{{pubName}}}.model.{{{classname}}} ## Load the model package ```dart -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; ``` ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#vars}}**{{{name}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/vars}} [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/modules/openapi-generator/src/main/resources/dart2/part_of.mustache b/modules/openapi-generator/src/main/resources/dart2/part_of.mustache new file mode 100644 index 000000000000..d9f1d409755c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/part_of.mustache @@ -0,0 +1 @@ +{{#pubLibrary}}part of {{{pubLibrary}}};{{/pubLibrary}}{{^pubLibrary}}part of {{{pubName}}}.api;{{/pubLibrary}} diff --git a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache index 88c70e22709f..c6c4a586deb0 100644 --- a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache @@ -1,14 +1,18 @@ -name: {{pubName}} -version: {{pubVersion}} -description: {{pubDescription}} +# +# AUTO-GENERATED FILE, DO NOT MODIFY! +# + +name: '{{{pubName}}}' +version: '{{{pubVersion}}}' +description: '{{{pubDescription}}}' authors: - - {{pubAuthor}} <{{pubAuthorEmail}}> -homepage: {{pubHomepage}} + - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' +homepage: '{{{pubHomepage}}}' environment: sdk: '>=2.0.0 <3.0.0' dependencies: http: '>=0.12.0 <0.13.0' - intl: ^0.16.1 - meta: ^1.1.8 + intl: '^0.16.1' + meta: '^1.1.8' dev_dependencies: - test: ^1.3.0 + test: '^1.3.0' diff --git a/modules/openapi-generator/src/main/resources/dart2/travis.mustache b/modules/openapi-generator/src/main/resources/dart2/travis.mustache index d0758bc9f0d6..1a3af66d54c7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/travis.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/travis.mustache @@ -1,3 +1,6 @@ +# +# AUTO-GENERATED FILE, DO NOT MODIFY! +# # https://docs.travis-ci.com/user/languages/dart/ # language: dart 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 be2e9ced0490..62693bf85447 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 @@ -41,6 +41,7 @@ protected CodegenConfig getCodegenConfig() { @Override protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(DartClientOptionsProvider.SORT_PARAMS_VALUE)); + verify(clientCodegen).setPubLibrary(DartClientOptionsProvider.PUB_LIBRARY_VALUE); verify(clientCodegen).setPubName(DartClientOptionsProvider.PUB_NAME_VALUE); verify(clientCodegen).setPubVersion(DartClientOptionsProvider.PUB_VERSION_VALUE); verify(clientCodegen).setPubDescription(DartClientOptionsProvider.PUB_DESCRIPTION_VALUE); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java index a5d349735799..8f1a3abcd4b3 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java @@ -41,6 +41,7 @@ protected CodegenConfig getCodegenConfig() { @Override protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(DartDioClientOptionsProvider.SORT_PARAMS_VALUE)); + verify(clientCodegen).setPubLibrary(DartDioClientOptionsProvider.PUB_LIBRARY_VALUE); verify(clientCodegen).setPubName(DartDioClientOptionsProvider.PUB_NAME_VALUE); verify(clientCodegen).setPubVersion(DartDioClientOptionsProvider.PUB_VERSION_VALUE); verify(clientCodegen).setPubDescription(DartDioClientOptionsProvider.PUB_DESCRIPTION_VALUE); 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 46f4a8013608..90d0ede4d003 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 @@ -28,6 +28,7 @@ public class DartClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "true"; public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String PUB_LIBRARY_VALUE = "openapi.api"; public static final String PUB_NAME_VALUE = "openapi"; public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String PUB_DESCRIPTION_VALUE = "OpenAPI API client dart"; @@ -50,6 +51,7 @@ public Map createOptions() { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(DartClientCodegen.PUB_LIBRARY, PUB_LIBRARY_VALUE) .put(DartClientCodegen.PUB_NAME, PUB_NAME_VALUE) .put(DartClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) .put(DartClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_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 d744501fa464..89186805c9c3 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 @@ -28,6 +28,7 @@ public class DartDioClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "true"; public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String PUB_LIBRARY_VALUE = "openapi.api"; public static final String PUB_NAME_VALUE = "openapi"; public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String PUB_DESCRIPTION_VALUE = "OpenAPI API client dart"; @@ -52,6 +53,7 @@ public Map createOptions() { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(DartDioClientCodegen.PUB_LIBRARY, PUB_LIBRARY_VALUE) .put(DartDioClientCodegen.PUB_NAME, PUB_NAME_VALUE) .put(DartDioClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) .put(DartDioClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE) diff --git a/samples/client/petstore/dart2/petstore_client_lib/.travis.yml b/samples/client/petstore/dart2/petstore_client_lib/.travis.yml index d0758bc9f0d6..1a3af66d54c7 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/.travis.yml +++ b/samples/client/petstore/dart2/petstore_client_lib/.travis.yml @@ -1,3 +1,6 @@ +# +# AUTO-GENERATED FILE, DO NOT MODIFY! +# # https://docs.travis-ci.com/user/languages/dart/ # language: dart diff --git a/samples/client/petstore/dart2/petstore_client_lib/README.md b/samples/client/petstore/dart2/petstore_client_lib/README.md index 1cf4ca28f0a8..0ebc02a14a66 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/README.md +++ b/samples/client/petstore/dart2/petstore_client_lib/README.md @@ -42,13 +42,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var body = Pet(); // Pet | Pet object that needs to be added to the store +final api_instance = PetApi(); +final body = Pet(); // Pet | Pet object that needs to be added to the store try { api_instance.addPet(body); } catch (e) { - print("Exception when calling PetApi->addPet: $e\n"); + print('Exception when calling PetApi->addPet: $e\n'); } ``` diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md index dc6c184bd030..88512ee37035 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md @@ -11,8 +11,8 @@ Name | Type | Description | Notes **id** | **int** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | -**photoUrls** | **List<String>** | | [default to const []] -**tags** | [**List<Tag>**](Tag.md) | | [optional] [default to const []] +**photoUrls** | **List** | | [default to const []] +**tags** | [**List**](Tag.md) | | [optional] [default to const []] **status** | **String** | pet status in the store | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md b/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md index cdd56362b2db..5342fcc3b7b2 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md @@ -30,13 +30,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var body = Pet(); // Pet | Pet object that needs to be added to the store +final api_instance = PetApi(); +final body = Pet(); // Pet | Pet object that needs to be added to the store try { api_instance.addPet(body); } catch (e) { - print("Exception when calling PetApi->addPet: $e\n"); + print('Exception when calling PetApi->addPet: $e\n'); } ``` @@ -72,14 +72,14 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var petId = 789; // int | Pet id to delete -var apiKey = apiKey_example; // String | +final api_instance = PetApi(); +final petId = 789; // int | Pet id to delete +final apiKey = apiKey_example; // String | try { api_instance.deletePet(petId, apiKey); } catch (e) { - print("Exception when calling PetApi->deletePet: $e\n"); + print('Exception when calling PetApi->deletePet: $e\n'); } ``` @@ -118,14 +118,14 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var status = []; // List | Status values that need to be considered for filter +final api_instance = PetApi(); +final status = []; // List | Status values that need to be considered for filter try { - var result = api_instance.findPetsByStatus(status); + final result = api_instance.findPetsByStatus(status); print(result); } catch (e) { - print("Exception when calling PetApi->findPetsByStatus: $e\n"); + print('Exception when calling PetApi->findPetsByStatus: $e\n'); } ``` @@ -133,7 +133,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [default to const []] + **status** | [**List**](String.md)| Status values that need to be considered for filter | [default to const []] ### Return type @@ -163,14 +163,14 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var tags = []; // List | Tags to filter by +final api_instance = PetApi(); +final tags = []; // List | Tags to filter by try { - var result = api_instance.findPetsByTags(tags); + final result = api_instance.findPetsByTags(tags); print(result); } catch (e) { - print("Exception when calling PetApi->findPetsByTags: $e\n"); + print('Exception when calling PetApi->findPetsByTags: $e\n'); } ``` @@ -178,7 +178,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**List<String>**](String.md)| Tags to filter by | [default to const []] + **tags** | [**List**](String.md)| Tags to filter by | [default to const []] ### Return type @@ -210,14 +210,14 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = PetApi(); -var petId = 789; // int | ID of pet to return +final api_instance = PetApi(); +final petId = 789; // int | ID of pet to return try { - var result = api_instance.getPetById(petId); + final result = api_instance.getPetById(petId); print(result); } catch (e) { - print("Exception when calling PetApi->getPetById: $e\n"); + print('Exception when calling PetApi->getPetById: $e\n'); } ``` @@ -253,13 +253,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var body = Pet(); // Pet | Pet object that needs to be added to the store +final api_instance = PetApi(); +final body = Pet(); // Pet | Pet object that needs to be added to the store try { api_instance.updatePet(body); } catch (e) { - print("Exception when calling PetApi->updatePet: $e\n"); + print('Exception when calling PetApi->updatePet: $e\n'); } ``` @@ -295,15 +295,15 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var petId = 789; // int | ID of pet that needs to be updated -var name = name_example; // String | Updated name of the pet -var status = status_example; // String | Updated status of the pet +final api_instance = PetApi(); +final petId = 789; // int | ID of pet that needs to be updated +final name = name_example; // String | Updated name of the pet +final status = status_example; // String | Updated status of the pet try { api_instance.updatePetWithForm(petId, name, status); } catch (e) { - print("Exception when calling PetApi->updatePetWithForm: $e\n"); + print('Exception when calling PetApi->updatePetWithForm: $e\n'); } ``` @@ -341,16 +341,16 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = PetApi(); -var petId = 789; // int | ID of pet to update -var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server -var file = BINARY_DATA_HERE; // MultipartFile | file to upload +final api_instance = PetApi(); +final petId = 789; // int | ID of pet to update +final additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +final file = BINARY_DATA_HERE; // MultipartFile | file to upload try { - var result = api_instance.uploadFile(petId, additionalMetadata, file); + final result = api_instance.uploadFile(petId, additionalMetadata, file); print(result); } catch (e) { - print("Exception when calling PetApi->uploadFile: $e\n"); + print('Exception when calling PetApi->uploadFile: $e\n'); } ``` diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md b/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md index 6ff167fc834f..a3bec5de59f6 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md @@ -26,13 +26,13 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```dart import 'package:openapi/api.dart'; -var api_instance = StoreApi(); -var orderId = orderId_example; // String | ID of the order that needs to be deleted +final api_instance = StoreApi(); +final orderId = orderId_example; // String | ID of the order that needs to be deleted try { api_instance.deleteOrder(orderId); } catch (e) { - print("Exception when calling StoreApi->deleteOrder: $e\n"); + print('Exception when calling StoreApi->deleteOrder: $e\n'); } ``` @@ -72,13 +72,13 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = StoreApi(); +final api_instance = StoreApi(); try { - var result = api_instance.getInventory(); + final result = api_instance.getInventory(); print(result); } catch (e) { - print("Exception when calling StoreApi->getInventory: $e\n"); + print('Exception when calling StoreApi->getInventory: $e\n'); } ``` @@ -111,14 +111,14 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```dart import 'package:openapi/api.dart'; -var api_instance = StoreApi(); -var orderId = 789; // int | ID of pet that needs to be fetched +final api_instance = StoreApi(); +final orderId = 789; // int | ID of pet that needs to be fetched try { - var result = api_instance.getOrderById(orderId); + final result = api_instance.getOrderById(orderId); print(result); } catch (e) { - print("Exception when calling StoreApi->getOrderById: $e\n"); + print('Exception when calling StoreApi->getOrderById: $e\n'); } ``` @@ -152,14 +152,14 @@ Place an order for a pet ```dart import 'package:openapi/api.dart'; -var api_instance = StoreApi(); -var body = Order(); // Order | order placed for purchasing the pet +final api_instance = StoreApi(); +final body = Order(); // Order | order placed for purchasing the pet try { - var result = api_instance.placeOrder(body); + final result = api_instance.placeOrder(body); print(result); } catch (e) { - print("Exception when calling StoreApi->placeOrder: $e\n"); + print('Exception when calling StoreApi->placeOrder: $e\n'); } ``` diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md b/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md index f3809ef73a35..711b6726a92e 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md @@ -30,13 +30,13 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var body = User(); // User | Created user object +final api_instance = UserApi(); +final body = User(); // User | Created user object try { api_instance.createUser(body); } catch (e) { - print("Exception when calling UserApi->createUser: $e\n"); + print('Exception when calling UserApi->createUser: $e\n'); } ``` @@ -70,13 +70,13 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var body = [List<User>()]; // List | List of user object +final api_instance = UserApi(); +final body = [List()]; // List | List of user object try { api_instance.createUsersWithArrayInput(body); } catch (e) { - print("Exception when calling UserApi->createUsersWithArrayInput: $e\n"); + print('Exception when calling UserApi->createUsersWithArrayInput: $e\n'); } ``` @@ -84,7 +84,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List<User>**](User.md)| List of user object | + **body** | [**List**](User.md)| List of user object | ### Return type @@ -110,13 +110,13 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var body = [List<User>()]; // List | List of user object +final api_instance = UserApi(); +final body = [List()]; // List | List of user object try { api_instance.createUsersWithListInput(body); } catch (e) { - print("Exception when calling UserApi->createUsersWithListInput: $e\n"); + print('Exception when calling UserApi->createUsersWithListInput: $e\n'); } ``` @@ -124,7 +124,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List<User>**](User.md)| List of user object | + **body** | [**List**](User.md)| List of user object | ### Return type @@ -152,13 +152,13 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var username = username_example; // String | The name that needs to be deleted +final api_instance = UserApi(); +final username = username_example; // String | The name that needs to be deleted try { api_instance.deleteUser(username); } catch (e) { - print("Exception when calling UserApi->deleteUser: $e\n"); + print('Exception when calling UserApi->deleteUser: $e\n'); } ``` @@ -192,14 +192,14 @@ Get user by user name ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var username = username_example; // String | The name that needs to be fetched. Use user1 for testing. +final api_instance = UserApi(); +final username = username_example; // String | The name that needs to be fetched. Use user1 for testing. try { - var result = api_instance.getUserByName(username); + final result = api_instance.getUserByName(username); print(result); } catch (e) { - print("Exception when calling UserApi->getUserByName: $e\n"); + print('Exception when calling UserApi->getUserByName: $e\n'); } ``` @@ -233,15 +233,15 @@ Logs user into the system ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var username = username_example; // String | The user name for login -var password = password_example; // String | The password for login in clear text +final api_instance = UserApi(); +final username = username_example; // String | The user name for login +final password = password_example; // String | The password for login in clear text try { - var result = api_instance.loginUser(username, password); + final result = api_instance.loginUser(username, password); print(result); } catch (e) { - print("Exception when calling UserApi->loginUser: $e\n"); + print('Exception when calling UserApi->loginUser: $e\n'); } ``` @@ -276,12 +276,12 @@ Logs out current logged in user session ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); +final api_instance = UserApi(); try { api_instance.logoutUser(); } catch (e) { - print("Exception when calling UserApi->logoutUser: $e\n"); + print('Exception when calling UserApi->logoutUser: $e\n'); } ``` @@ -314,14 +314,14 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var username = username_example; // String | name that need to be deleted -var body = User(); // User | Updated user object +final api_instance = UserApi(); +final username = username_example; // String | name that need to be deleted +final body = User(); // User | Updated user object try { api_instance.updateUser(username, body); } catch (e) { - print("Exception when calling UserApi->updateUser: $e\n"); + print('Exception when calling UserApi->updateUser: $e\n'); } ``` diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart index baf59a69c137..5fa4f759553d 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -1,7 +1,18 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + library openapi.api; import 'dart:async'; import 'dart:convert'; +import 'dart:io'; + import 'package:http/http.dart'; import 'package:intl/intl.dart'; import 'package:meta/meta.dart'; @@ -26,5 +37,10 @@ part 'model/pet.dart'; part 'model/tag.dart'; part 'model/user.dart'; +const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; +const _dateEpochMarker = 'epoch'; +final _dateFormatter = DateFormat('yyyy-MM-dd'); +final _regList = RegExp(r'^List<(.*)>$'); +final _regMap = RegExp(r'^Map$'); ApiClient defaultApiClient = ApiClient(); diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart index 56efbc2492bc..772154d7801f 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart @@ -1,401 +1,487 @@ -part of openapi.api; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars +part of openapi.api; -class PetApi { - final ApiClient apiClient; +class PetApi { PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; - /// Add a new pet to the store with HTTP info returned + final ApiClient apiClient; + + /// Add a new pet to the store + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [Pet] body (required): + /// Pet object that needs to be added to the store Future addPetWithHttpInfo(Pet body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/pet".replaceAll("{format}","json"); + final path = '/pet'.replaceAll('{format}', 'json'); + + Object postBody = body; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = ["application/json","application/xml"]; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = ['application/json', 'application/xml']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Add a new pet to the store /// - ///Pet body (required): - /// Pet object that needs to be added to the store - /// + /// Parameters: + /// + /// * [Pet] body (required): + /// Pet object that needs to be added to the store Future addPet(Pet body) async { - Response response = await addPetWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await addPetWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Deletes a pet with HTTP info returned + /// Deletes a pet + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [int] petId (required): + /// Pet id to delete + /// + /// * [String] apiKey: Future deletePetWithHttpInfo(int petId, { String apiKey }) async { - Object postBody; - - // verify required params are set - if(petId == null) { - throw ApiException(400, "Missing required param: petId"); + // Verify required params are set. + if (petId == null) { + throw ApiException(400, 'Missing required param: petId'); } - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + final path = '/pet/{petId}'.replaceAll('{format}', 'json').replaceAll('{' + 'petId' + '}', petId.toString()); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - headerParams["api_key"] = apiKey; + Object postBody; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; + headerParams['api_key'] = apiKey; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'DELETE', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Deletes a pet /// - ///int petId (required): - /// Pet id to delete - ///String apiKey : - /// - /// + /// Parameters: + /// + /// * [int] petId (required): + /// Pet id to delete + /// + /// * [String] apiKey: Future deletePet(int petId, { String apiKey }) async { - Response response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); - if(response.statusCode >= 400) { + final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Finds Pets by status with HTTP info returned + /// Finds Pets by status /// /// Multiple status values can be provided with comma separated strings + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [List] status (required): + /// Status values that need to be considered for filter Future findPetsByStatusWithHttpInfo(List status) async { - Object postBody; - - // verify required params are set - if(status == null) { - throw ApiException(400, "Missing required param: status"); + // Verify required params are set. + if (status == null) { + throw ApiException(400, 'Missing required param: status'); } - // create path and map variables - String path = "/pet/findByStatus".replaceAll("{format}","json"); + final path = '/pet/findByStatus'.replaceAll('{format}', 'json'); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat("csv", "status", status)); + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; + queryParams.addAll(_convertParametersForCollectionFormat('csv', 'status', status)); - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Finds Pets by status /// - ///List<String> status (required): - /// Status values that need to be considered for filter /// Multiple status values can be provided with comma separated strings + /// + /// Parameters: + /// + /// * [List] status (required): + /// Status values that need to be considered for filter Future> findPetsByStatus(List status) async { - Response response = await findPetsByStatusWithHttpInfo(status); - if(response.statusCode >= 400) { + final response = await findPetsByStatusWithHttpInfo(status); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); - } else { - return null; } + if (response.body != null) { + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + .map((item) => item as Pet) + .toList(growable: false); + } + return null; } - /// Finds Pets by tags with HTTP info returned + /// Finds Pets by tags /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [List] tags (required): + /// Tags to filter by Future findPetsByTagsWithHttpInfo(List tags) async { - Object postBody; - - // verify required params are set - if(tags == null) { - throw ApiException(400, "Missing required param: tags"); + // Verify required params are set. + if (tags == null) { + throw ApiException(400, 'Missing required param: tags'); } - // create path and map variables - String path = "/pet/findByTags".replaceAll("{format}","json"); + final path = '/pet/findByTags'.replaceAll('{format}', 'json'); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat("csv", "tags", tags)); + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; + queryParams.addAll(_convertParametersForCollectionFormat('csv', 'tags', tags)); - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Finds Pets by tags /// - ///List<String> tags (required): - /// Tags to filter by /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Parameters: + /// + /// * [List] tags (required): + /// Tags to filter by Future> findPetsByTags(List tags) async { - Response response = await findPetsByTagsWithHttpInfo(tags); - if(response.statusCode >= 400) { + final response = await findPetsByTagsWithHttpInfo(tags); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); - } else { - return null; } + if (response.body != null) { + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + .map((item) => item as Pet) + .toList(growable: false); + } + return null; } - /// Find pet by ID with HTTP info returned + /// Find pet by ID /// /// Returns a single pet + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet to return Future getPetByIdWithHttpInfo(int petId) async { - Object postBody; - - // verify required params are set - if(petId == null) { - throw ApiException(400, "Missing required param: petId"); + // Verify required params are set. + if (petId == null) { + throw ApiException(400, 'Missing required param: petId'); } - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + final path = '/pet/{petId}'.replaceAll('{format}', 'json').replaceAll('{' + 'petId' + '}', petId.toString()); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + Object postBody; - List contentTypes = []; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["api_key"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['api_key']; + + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Find pet by ID /// - ///int petId (required): - /// ID of pet to return /// Returns a single pet + /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet to return Future getPetById(int petId) async { - Response response = await getPetByIdWithHttpInfo(petId); - if(response.statusCode >= 400) { + final response = await getPetByIdWithHttpInfo(petId); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; - } else { - return null; } + return null; } - /// Update an existing pet with HTTP info returned + /// Update an existing pet + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [Pet] body (required): + /// Pet object that needs to be added to the store Future updatePetWithHttpInfo(Pet body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/pet".replaceAll("{format}","json"); + final path = '/pet'.replaceAll('{format}', 'json'); + + Object postBody = body; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = ["application/json","application/xml"]; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = ['application/json', 'application/xml']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'PUT', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Update an existing pet /// - ///Pet body (required): - /// Pet object that needs to be added to the store - /// + /// Parameters: + /// + /// * [Pet] body (required): + /// Pet object that needs to be added to the store Future updatePet(Pet body) async { - Response response = await updatePetWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await updatePetWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Updates a pet in the store with form data with HTTP info returned + /// Updates a pet in the store with form data + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet that needs to be updated /// - /// + /// * [String] name: + /// Updated name of the pet + /// + /// * [String] status: + /// Updated status of the pet Future updatePetWithFormWithHttpInfo(int petId, { String name, String status }) async { - Object postBody; - - // verify required params are set - if(petId == null) { - throw ApiException(400, "Missing required param: petId"); + // Verify required params are set. + if (petId == null) { + throw ApiException(400, 'Missing required param: petId'); } - // create path and map variables - String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + final path = '/pet/{petId}'.replaceAll('{format}', 'json').replaceAll('{' + 'petId' + '}', petId.toString()); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + Object postBody; - List contentTypes = ["application/x-www-form-urlencoded"]; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + final contentTypes = ['application/x-www-form-urlencoded']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; + + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (name != null) { hasFields = true; mp.fields['name'] = parameterToString(name); @@ -404,73 +490,91 @@ class PetApi { hasFields = true; mp.fields['status'] = parameterToString(status); } - if(hasFields) + if (hasFields) { postBody = mp; - } - else { - if (name != null) + } + } else { + if (name != null) { formParams['name'] = parameterToString(name); - if (status != null) + } + if (status != null) { formParams['status'] = parameterToString(status); + } } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Updates a pet in the store with form data /// - ///int petId (required): - /// ID of pet that needs to be updated - ///String name : - /// Updated name of the pet - ///String status : - /// Updated status of the pet - /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet that needs to be updated + /// + /// * [String] name: + /// Updated name of the pet + /// + /// * [String] status: + /// Updated status of the pet Future updatePetWithForm(int petId, { String name, String status }) async { - Response response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); - if(response.statusCode >= 400) { + final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// uploads an image with HTTP info returned + /// uploads an image + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet to update /// - /// + /// * [String] additionalMetadata: + /// Additional data to pass to server + /// + /// * [MultipartFile] file: + /// file to upload Future uploadFileWithHttpInfo(int petId, { String additionalMetadata, MultipartFile file }) async { - Object postBody; - - // verify required params are set - if(petId == null) { - throw ApiException(400, "Missing required param: petId"); + // Verify required params are set. + if (petId == null) { + throw ApiException(400, 'Missing required param: petId'); } - // create path and map variables - String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + final path = '/pet/{petId}/uploadImage'.replaceAll('{format}', 'json').replaceAll('{' + 'petId' + '}', petId.toString()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = ["multipart/form-data"]; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = ['multipart/form-data']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (additionalMetadata != null) { hasFields = true; mp.fields['additionalMetadata'] = parameterToString(additionalMetadata); @@ -480,43 +584,47 @@ class PetApi { mp.fields['file'] = file.field; mp.files.add(file); } - if(hasFields) + if (hasFields) { postBody = mp; - } - else { - if (additionalMetadata != null) + } + } else { + if (additionalMetadata != null) { formParams['additionalMetadata'] = parameterToString(additionalMetadata); + } } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// uploads an image /// - ///int petId (required): - /// ID of pet to update - ///String additionalMetadata : - /// Additional data to pass to server - ///MultipartFile file : - /// file to upload - /// + /// Parameters: + /// + /// * [int] petId (required): + /// ID of pet to update + /// + /// * [String] additionalMetadata: + /// Additional data to pass to server + /// + /// * [MultipartFile] file: + /// file to upload Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { - Response response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); - if(response.statusCode >= 400) { + final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; - } else { - return null; } + return null; } - } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart index 3c10ba5454ca..dbb8b77da2ad 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart @@ -1,245 +1,287 @@ -part of openapi.api; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars +part of openapi.api; -class StoreApi { - final ApiClient apiClient; +class StoreApi { StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; - /// Delete purchase order by ID with HTTP info returned + final ApiClient apiClient; + + /// Delete purchase order by ID + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: /// - /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// * [String] orderId (required): + /// ID of the order that needs to be deleted Future deleteOrderWithHttpInfo(String orderId) async { - Object postBody; - - // verify required params are set - if(orderId == null) { - throw ApiException(400, "Missing required param: orderId"); + // Verify required params are set. + if (orderId == null) { + throw ApiException(400, 'Missing required param: orderId'); } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + final path = '/store/order/{orderId}'.replaceAll('{format}', 'json').replaceAll('{' + 'orderId' + '}', orderId.toString()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'DELETE', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Delete purchase order by ID /// - ///String orderId (required): - /// ID of the order that needs to be deleted - /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Parameters: + /// + /// * [String] orderId (required): + /// ID of the order that needs to be deleted Future deleteOrder(String orderId) async { - Response response = await deleteOrderWithHttpInfo(orderId); - if(response.statusCode >= 400) { + final response = await deleteOrderWithHttpInfo(orderId); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Returns pet inventories by status with HTTP info returned + /// Returns pet inventories by status /// /// Returns a map of status codes to quantities + /// + /// Note: This method returns the HTTP [Response]. Future getInventoryWithHttpInfo() async { - Object postBody; + // Verify required params are set. - // verify required params are set + final path = '/store/inventory'.replaceAll('{format}', 'json'); - // create path and map variables - String path = "/store/inventory".replaceAll("{format}","json"); + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["api_key"]; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['api_key']; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Returns pet inventories by status /// /// Returns a map of status codes to quantities Future> getInventory() async { - Response response = await getInventoryWithHttpInfo(); - if(response.statusCode >= 400) { + final response = await getInventoryWithHttpInfo(); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); - ; - } else { - return null; } + return null; } - /// Find purchase order by ID with HTTP info returned + /// Find purchase order by ID + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Note: This method returns the HTTP [Response]. /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// Parameters: + /// + /// * [int] orderId (required): + /// ID of pet that needs to be fetched Future getOrderByIdWithHttpInfo(int orderId) async { - Object postBody; - - // verify required params are set - if(orderId == null) { - throw ApiException(400, "Missing required param: orderId"); + // Verify required params are set. + if (orderId == null) { + throw ApiException(400, 'Missing required param: orderId'); } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + final path = '/store/order/{orderId}'.replaceAll('{format}', 'json').replaceAll('{' + 'orderId' + '}', orderId.toString()); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + Object postBody; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Find purchase order by ID /// - ///int orderId (required): - /// ID of pet that needs to be fetched - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Parameters: + /// + /// * [int] orderId (required): + /// ID of pet that needs to be fetched Future getOrderById(int orderId) async { - Response response = await getOrderByIdWithHttpInfo(orderId); - if(response.statusCode >= 400) { + final response = await getOrderByIdWithHttpInfo(orderId); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; - } else { - return null; } + return null; } - /// Place an order for a pet with HTTP info returned + /// Place an order for a pet + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: /// - /// + /// * [Order] body (required): + /// order placed for purchasing the pet Future placeOrderWithHttpInfo(Order body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/store/order".replaceAll("{format}","json"); + final path = '/store/order'.replaceAll('{format}', 'json'); + + Object postBody = body; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Place an order for a pet /// - ///Order body (required): - /// order placed for purchasing the pet - /// + /// Parameters: + /// + /// * [Order] body (required): + /// order placed for purchasing the pet Future placeOrder(Order body) async { - Response response = await placeOrderWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await placeOrderWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; - } else { - return null; } + return null; } - } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart index ea069b58ea80..e6c8c89d4499 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart @@ -1,491 +1,574 @@ -part of openapi.api; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars +part of openapi.api; -class UserApi { - final ApiClient apiClient; +class UserApi { UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; - /// Create user with HTTP info returned + final ApiClient apiClient; + + /// Create user /// /// This can only be done by the logged in user. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [User] body (required): + /// Created user object Future createUserWithHttpInfo(User body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/user".replaceAll("{format}","json"); + final path = '/user'.replaceAll('{format}', 'json'); + + Object postBody = body; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Create user /// - ///User body (required): - /// Created user object /// This can only be done by the logged in user. + /// + /// Parameters: + /// + /// * [User] body (required): + /// Created user object Future createUser(User body) async { - Response response = await createUserWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await createUserWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Creates list of users with given input array with HTTP info returned + /// Creates list of users with given input array + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [List] body (required): + /// List of user object Future createUsersWithArrayInputWithHttpInfo(List body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/user/createWithArray".replaceAll("{format}","json"); + final path = '/user/createWithArray'.replaceAll('{format}', 'json'); + + Object postBody = body; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Creates list of users with given input array /// - ///List<User> body (required): - /// List of user object - /// + /// Parameters: + /// + /// * [List] body (required): + /// List of user object Future createUsersWithArrayInput(List body) async { - Response response = await createUsersWithArrayInputWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await createUsersWithArrayInputWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Creates list of users with given input array with HTTP info returned + /// Creates list of users with given input array + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [List] body (required): + /// List of user object Future createUsersWithListInputWithHttpInfo(List body) async { - Object postBody = body; - - // verify required params are set - if(body == null) { - throw ApiException(400, "Missing required param: body"); + // Verify required params are set. + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/user/createWithList".replaceAll("{format}","json"); + final path = '/user/createWithList'.replaceAll('{format}', 'json'); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + Object postBody = body; - List contentTypes = []; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'POST', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Creates list of users with given input array /// - ///List<User> body (required): - /// List of user object - /// + /// Parameters: + /// + /// * [List] body (required): + /// List of user object Future createUsersWithListInput(List body) async { - Response response = await createUsersWithListInputWithHttpInfo(body); - if(response.statusCode >= 400) { + final response = await createUsersWithListInputWithHttpInfo(body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Delete user with HTTP info returned + /// Delete user /// /// This can only be done by the logged in user. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [String] username (required): + /// The name that needs to be deleted Future deleteUserWithHttpInfo(String username) async { - Object postBody; - - // verify required params are set - if(username == null) { - throw ApiException(400, "Missing required param: username"); + // Verify required params are set. + if (username == null) { + throw ApiException(400, 'Missing required param: username'); } - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + final path = '/user/{username}'.replaceAll('{format}', 'json').replaceAll('{' + 'username' + '}', username.toString()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'DELETE', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Delete user /// - ///String username (required): - /// The name that needs to be deleted /// This can only be done by the logged in user. + /// + /// Parameters: + /// + /// * [String] username (required): + /// The name that needs to be deleted Future deleteUser(String username) async { - Response response = await deleteUserWithHttpInfo(username); - if(response.statusCode >= 400) { + final response = await deleteUserWithHttpInfo(username); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Get user by user name with HTTP info returned + /// Get user by user name + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: /// - /// + /// * [String] username (required): + /// The name that needs to be fetched. Use user1 for testing. Future getUserByNameWithHttpInfo(String username) async { - Object postBody; - - // verify required params are set - if(username == null) { - throw ApiException(400, "Missing required param: username"); + // Verify required params are set. + if (username == null) { + throw ApiException(400, 'Missing required param: username'); } - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + final path = '/user/{username}'.replaceAll('{format}', 'json').replaceAll('{' + 'username' + '}', username.toString()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Get user by user name /// - ///String username (required): - /// The name that needs to be fetched. Use user1 for testing. - /// + /// Parameters: + /// + /// * [String] username (required): + /// The name that needs to be fetched. Use user1 for testing. Future getUserByName(String username) async { - Response response = await getUserByNameWithHttpInfo(username); - if(response.statusCode >= 400) { + final response = await getUserByNameWithHttpInfo(username); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; - } else { - return null; } + return null; } - /// Logs user into the system with HTTP info returned + /// Logs user into the system + /// + /// Note: This method returns the HTTP [Response]. /// - /// + /// Parameters: + /// + /// * [String] username (required): + /// The user name for login + /// + /// * [String] password (required): + /// The password for login in clear text Future loginUserWithHttpInfo(String username, String password) async { - Object postBody; - - // verify required params are set - if(username == null) { - throw ApiException(400, "Missing required param: username"); + // Verify required params are set. + if (username == null) { + throw ApiException(400, 'Missing required param: username'); } - if(password == null) { - throw ApiException(400, "Missing required param: password"); + if (password == null) { + throw ApiException(400, 'Missing required param: password'); } - // create path and map variables - String path = "/user/login".replaceAll("{format}","json"); + final path = '/user/login'.replaceAll('{format}', 'json'); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); - queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; + queryParams.addAll(_convertParametersForCollectionFormat('', 'username', username)); + queryParams.addAll(_convertParametersForCollectionFormat('', 'password', password)); - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Logs user into the system /// - ///String username (required): - /// The user name for login - ///String password (required): - /// The password for login in clear text - /// + /// Parameters: + /// + /// * [String] username (required): + /// The user name for login + /// + /// * [String] password (required): + /// The password for login in clear text Future loginUser(String username, String password) async { - Response response = await loginUserWithHttpInfo(username, password); - if(response.statusCode >= 400) { + final response = await loginUserWithHttpInfo(username, password); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { + } + if (response.body != null) { return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; - } else { - return null; } + return null; } - /// Logs out current logged in user session with HTTP info returned + /// Logs out current logged in user session /// - /// + /// Note: This method returns the HTTP [Response]. Future logoutUserWithHttpInfo() async { - Object postBody; + // Verify required params are set. - // verify required params are set + final path = '/user/logout'.replaceAll('{format}', 'json'); - // create path and map variables - String path = "/user/logout".replaceAll("{format}","json"); + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = []; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'GET', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Logs out current logged in user session - /// - /// Future logoutUser() async { - Response response = await logoutUserWithHttpInfo(); - if(response.statusCode >= 400) { + final response = await logoutUserWithHttpInfo(); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - /// Updated user with HTTP info returned + /// Updated user /// /// This can only be done by the logged in user. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [String] username (required): + /// name that need to be deleted + /// + /// * [User] body (required): + /// Updated user object Future updateUserWithHttpInfo(String username, User body) async { - Object postBody = body; - - // verify required params are set - if(username == null) { - throw ApiException(400, "Missing required param: username"); + // Verify required params are set. + if (username == null) { + throw ApiException(400, 'Missing required param: username'); } - if(body == null) { - throw ApiException(400, "Missing required param: body"); + if (body == null) { + throw ApiException(400, 'Missing required param: body'); } - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + final path = '/user/{username}'.replaceAll('{format}', 'json').replaceAll('{' + 'username' + '}', username.toString()); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + Object postBody = body; - List contentTypes = []; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + if ( + nullableContentType != null && + nullableContentType.toLowerCase().startsWith('multipart/form-data') + ) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + final mp = MultipartRequest(null, null); + if (hasFields) { postBody = mp; - } - else { + } + } else { } - var response = await apiClient.invokeAPI(path, - 'PUT', - queryParams, - postBody, - headerParams, - formParams, - nullableContentType, - authNames); - return response; + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); } /// Updated user /// - ///String username (required): - /// name that need to be deleted - ///User body (required): - /// Updated user object /// This can only be done by the logged in user. + /// + /// Parameters: + /// + /// * [String] username (required): + /// name that need to be deleted + /// + /// * [User] body (required): + /// Updated user object Future updateUser(String username, User body) async { - Response response = await updateUserWithHttpInfo(username, body); - if(response.statusCode >= 400) { + final response = await updateUserWithHttpInfo(username, body); + if (response.statusCode >= 400) { throw ApiException(response.statusCode, _decodeBodyBytes(response)); - } else if(response.body != null) { - } else { - return; } + if (response.body != null) { + } + return; } - } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index d68c9691879f..2d86d6f338fd 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -1,34 +1,136 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class QueryParam { + QueryParam(this.name, this.value); + String name; String value; - - QueryParam(this.name, this.value); } class ApiClient { + ApiClient({this.basePath = 'http://petstore.swagger.io/v2'}) { + // Setup authentications (key: authentication name, value: authentication). + _authentications['api_key'] = ApiKeyAuth('header', 'api_key'); + _authentications['petstore_auth'] = OAuth(); + } - String basePath; - var client = Client(); + final String basePath; - Map _defaultHeaderMap = {}; - Map _authentications = {}; + var _client = Client(); - final _regList = RegExp(r'^List<(.*)>$'); - final _regMap = RegExp(r'^Map$'); + /// Returns the current HTTP [Client] instance to use in this class. + /// + /// The return value is guaranteed to never be null. + Client get client => _client; - ApiClient({this.basePath = "http://petstore.swagger.io/v2"}) { - // Setup authentications (key: authentication name, value: authentication). - _authentications['api_key'] = ApiKeyAuth("header", "api_key"); - _authentications['petstore_auth'] = OAuth(); + /// Requests to use a new HTTP [Client] in this class. + /// + /// If the [newClient] is null, an [ArgumentError] is thrown. + set client(Client newClient) { + if (newClient == null) { + throw ArgumentError('New client instance cannot be null.'); + } + _client = newClient; } + final _defaultHeaderMap = {}; + final _authentications = {}; + void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - dynamic _deserialize(dynamic value, String targetType) { + dynamic deserialize(String json, String targetType, {bool growable}) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); + + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: true == growable); + } + + String serialize(Object obj) => obj == null ? '' : json.encode(obj); + + T getAuthentication(String name) { + final authentication = _authentications[name]; + return authentication is T ? authentication : null; + } + + // We don’t use a Map for queryParams. + // If collectionFormat is 'multi', a key might appear multiple times. + Future invokeAPI( + String path, + String method, + Iterable queryParams, + Object body, + Map headerParams, + Map formParams, + String nullableContentType, + List authNames, + ) async { + _updateParamsForAuth(authNames, queryParams, headerParams); + + headerParams.addAll(_defaultHeaderMap); + + final ps = queryParams + .where((p) => p.value != null) + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); + + final queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; + + final url = '$basePath$path$queryString'; + + if (nullableContentType != null) { + headerParams['Content-Type'] = nullableContentType; + } + + if (body is MultipartRequest) { + final request = MultipartRequest(method, Uri.parse(url)); + request.fields.addAll(body.fields); + request.files.addAll(body.files); + request.headers.addAll(body.headers); + request.headers.addAll(headerParams); + final response = await _client.send(request); + return Response.fromStream(response); + } + + final msgBody = nullableContentType == 'application/x-www-form-urlencoded' + ? formParams + : serialize(body); + final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; + + try { + switch(method) { + case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody); + case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody); + case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams); + case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody); + case 'HEAD': return await _client.head(url, headers: nullableHeaderParams); + case 'GET': return await _client.get(url, headers: nullableHeaderParams); + } + } on SocketException catch (e, trace) { + throw ApiException.withInner(400, 'Socket operation failed: $method $path', e, trace); + } on TlsException catch (e, trace) { + throw ApiException.withInner(400, 'TLS/SSL communication failed: $method $path', e, trace); + } on IOException catch (e, trace) { + throw ApiException.withInner(400, 'I/O operation failed: $method $path', e, trace); + } on Exception catch (e, trace) { + throw ApiException.withInner(400, 'Exception occurred: $method $path', e, trace); + } + + throw ApiException(400, 'Invalid HTTP operation: $method $path'); + } + + dynamic _deserialize(dynamic value, String targetType, {bool growable}) { try { switch (targetType) { case 'String': @@ -36,7 +138,12 @@ class ApiClient { case 'int': return value is int ? value : int.parse('$value'); case 'bool': - return value is bool ? value : '$value'.toLowerCase() == 'true'; + if (value is bool) { + return value; + } + final valueString = '$value'.toLowerCase(); + return valueString == 'true' || valueString == '1'; + break; case 'double': return value is double ? value : double.parse('$value'); case 'ApiResponse': @@ -52,19 +159,21 @@ class ApiClient { case 'User': return User.fromJson(value); default: - { - Match match; - if (value is List && - (match = _regList.firstMatch(targetType)) != null) { - var newTargetType = match[1]; - return value.map((v) => _deserialize(v, newTargetType)).toList(); - } else if (value is Map && - (match = _regMap.firstMatch(targetType)) != null) { - var newTargetType = match[1]; - return Map.fromIterables(value.keys, - value.values.map((v) => _deserialize(v, newTargetType))); - } + Match match; + if (value is List && (match = _regList.firstMatch(targetType)) != null) { + final newTargetType = match[1]; + return value + .map((v) => _deserialize(v, newTargetType, growable: growable)) + .toList(growable: true == growable); } + if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { + final newTargetType = match[1]; + return Map.fromIterables( + value.keys, + value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + ); + } + break; } } on Exception catch (e, stack) { throw ApiException.withInner(500, 'Exception during deserialization.', e, stack); @@ -72,96 +181,19 @@ class ApiClient { throw ApiException(500, 'Could not find a suitable class for deserialization'); } - dynamic deserialize(String json, String targetType) { - // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(' ', ''); - - if (targetType == 'String') return json; - - var decodedJson = jsonDecode(json); - return _deserialize(decodedJson, targetType); - } - - String serialize(Object obj) { - String serialized = ''; - if (obj == null) { - serialized = ''; - } else { - serialized = json.encode(obj); - } - return serialized; - } - - // We don't use a Map for queryParams. - // If collectionFormat is 'multi' a key might appear multiple times. - Future invokeAPI(String path, - String method, - Iterable queryParams, - Object body, - Map headerParams, - Map formParams, - String nullableContentType, - List authNames) async { - - _updateParamsForAuth(authNames, queryParams, headerParams); - - var ps = queryParams - .where((p) => p.value != null) - .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); - - String queryString = ps.isNotEmpty ? - '?' + ps.join('&') : - ''; - - String url = basePath + path + queryString; - - headerParams.addAll(_defaultHeaderMap); - if (nullableContentType != null) { - final contentType = nullableContentType; - headerParams['Content-Type'] = contentType; - } - - if(body is MultipartRequest) { - var request = MultipartRequest(method, Uri.parse(url)); - request.fields.addAll(body.fields); - request.files.addAll(body.files); - request.headers.addAll(body.headers); - request.headers.addAll(headerParams); - var response = await client.send(request); - return Response.fromStream(response); - } else { - var msgBody = nullableContentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); - final nullableHeaderParams = (headerParams.isEmpty)? null: headerParams; - switch(method) { - case "POST": - return client.post(url, headers: nullableHeaderParams, body: msgBody); - case "PUT": - return client.put(url, headers: nullableHeaderParams, body: msgBody); - case "DELETE": - return client.delete(url, headers: nullableHeaderParams); - case "PATCH": - return client.patch(url, headers: nullableHeaderParams, body: msgBody); - case "HEAD": - return client.head(url, headers: nullableHeaderParams); - default: - return client.get(url, headers: nullableHeaderParams); - } - } - } - /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { authNames.forEach((authName) { - Authentication auth = _authentications[authName]; - if (auth == null) throw ArgumentError("Authentication undefined: " + authName); + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } auth.applyToParams(queryParams, headerParams); }); } - - T getAuthentication(String name) { - var authentication = _authentications[name]; - - return authentication is T ? authentication : null; - } } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart index 668abe2c96bc..1537c9769b21 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart @@ -1,23 +1,31 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class ApiException implements Exception { + ApiException(this.code, this.message); + + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + int code = 0; String message; Exception innerException; StackTrace stackTrace; - ApiException(this.code, this.message); - - ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); - String toString() { - if (message == null) return "ApiException"; - + if (message == null) { + return 'ApiException'; + } if (innerException == null) { - return "ApiException $code: $message"; + return 'ApiException $code: $message'; } - - return "ApiException $code: $message (Inner exception: $innerException)\n\n" + - stackTrace.toString(); + return 'ApiException $code: $message (Inner exception: $innerException)\n\n$stackTrace'; } } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart index 919e442caf14..4eed380b5001 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart @@ -1,57 +1,61 @@ -part of openapi.api; +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars -const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; -var _dateFormatter = DateFormat('yyyy-MM-dd'); +part of openapi.api; -// port from Java version +// Ported from the Java version. Iterable _convertParametersForCollectionFormat( - String collectionFormat, String name, dynamic value) { - var params = []; + String collectionFormat, + String name, + dynamic value, +) { + final params = []; // preconditions - if (name == null || name.isEmpty || value == null) return params; - - if (value is! List) { - params.add(QueryParam(name, parameterToString(value))); - return params; + if (name != null && !name.isEmpty && value != null) { + if (value is List) { + // get the collection format, default: csv + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? 'csv' + : collectionFormat; + + if (collectionFormat == 'multi') { + return value.map((v) => QueryParam(name, parameterToString(v))); + } + + final delimiter = _delimiters[collectionFormat] ?? ','; + + params.add(QueryParam(name, value.map((v) => parameterToString(v)).join(delimiter))); + } else { + params.add(QueryParam(name, parameterToString(value))); + } } - List values = value as List; - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" - : collectionFormat; // default: csv - - if (collectionFormat == "multi") { - return values.map((v) => QueryParam(name, parameterToString(v))); - } - - String delimiter = _delimiters[collectionFormat] ?? ","; - - params.add(QueryParam(name, values.map((v) => parameterToString(v)).join(delimiter))); return params; } -/// Format the given parameter object into string. +/// Format the given parameter object into a [String]. String parameterToString(dynamic value) { if (value == null) { return ''; - } else if (value is DateTime) { + } + if (value is DateTime) { return value.toUtc().toIso8601String(); - } else { - return value.toString(); } + return value.toString(); } -/// Returns the decoded body by utf-8 if application/json with the given headers. -/// Else, returns the decoded body by default algorithm of dart:http. -/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +/// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json' +/// content type. Otherwise, returns the decoded body as decoded by dart:http package. String _decodeBodyBytes(Response response) { - var contentType = response.headers['content-type']; - if (contentType != null && contentType.contains("application/json")) { - return utf8.decode(response.bodyBytes); - } else { - return response.body; - } + final contentType = response.headers['content-type']; + return contentType != null && contentType.contains('application/json') + ? utf8.decode(response.bodyBytes) + : response.body; } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart index 78ffb2e0a216..41a4afd85d90 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart @@ -1,24 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class ApiKeyAuth implements Authentication { + ApiKeyAuth(this.location, this.paramName); final String location; final String paramName; - String _apiKey; - String apiKeyPrefix; - set apiKey(String key) => _apiKey = key; - - ApiKeyAuth(this.location, this.paramName); + String apiKeyPrefix; + String apiKey; @override void applyToParams(List queryParams, Map headerParams) { - String value; - if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $_apiKey'; - } else { - value = _apiKey; - } + final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; if (location == 'query' && value != null) { queryParams.add(QueryParam(paramName, value)); @@ -26,7 +28,7 @@ class ApiKeyAuth implements Authentication { headerParams[paramName] = value; } else if (location == 'cookie' && value != null) { headerParams.update('Cookie', (String existingCookie) { - return "$existingCookie; $paramName=$value"; + return '$existingCookie; $paramName=$value'; }, ifAbsent: () => '$paramName=$value'); } } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart index abd5e2fe68a3..5ca198d41fdb 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart @@ -1,7 +1,15 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; abstract class Authentication { - - /// Apply authentication settings to header and query params. - void applyToParams(List queryParams, Map headerParams); + /// Apply authentication settings to header and query params. + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart index da931fa2634c..6dc36a13f497 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart @@ -1,16 +1,21 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class HttpBasicAuth implements Authentication { - - String _username; - String _password; + String username; + String password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); - headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); + final credentials = (username ?? '') + ':' + (password ?? ''); + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; } - - set username(String username) => _username = username; - set password(String password) => _password = password; } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart index 19a348c965ed..a23b65fac5ed 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart @@ -1,25 +1,38 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; +typedef HttpBearerAuthProvider = String Function(); + class HttpBearerAuth implements Authentication { + HttpBearerAuth(); + dynamic _accessToken; - HttpBearerAuth() { } + dynamic get accessToken => _accessToken; + + set accessToken(dynamic accessToken) { + if (accessToken is! String && accessToken is! HttpBearerAuthProvider) { + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + } + this._accessToken = accessToken; + } @override void applyToParams(List queryParams, Map headerParams) { if (_accessToken is String) { - headerParams["Authorization"] = "Bearer " + _accessToken; - } else if (_accessToken is String Function()){ - headerParams["Authorization"] = "Bearer " + _accessToken(); + headerParams['Authorization'] = 'Bearer $_accessToken'; + } else if (_accessToken is HttpBearerAuthProvider) { + headerParams['Authorization'] = 'Bearer ${_accessToken()}'; } else { - throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } } - - void setAccessToken(dynamic accessToken) { - if (!((accessToken is String) | (accessToken is String Function()))){ - throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); - } - this._accessToken = accessToken; - } } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart index 230471e44fc6..c0463ad39008 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart @@ -1,16 +1,23 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class OAuth implements Authentication { - String _accessToken; + OAuth({this.accessToken}); - OAuth({String accessToken}) : _accessToken = accessToken; + String accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (_accessToken != null) { - headerParams["Authorization"] = "Bearer $_accessToken"; + if (accessToken != null) { + headerParams['Authorization'] = 'Bearer $accessToken'; } } - - set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart index 423d533a97b6..04e7edc10770 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart @@ -1,60 +1,89 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class ApiResponse { + /// Returns a new [ApiResponse] instance. + ApiResponse({ + this.code, + this.type, + this.message, + }); + + /// Returns a new [ApiResponse] instance and optionally import its values from + /// [json] if it's non-null. + ApiResponse.fromJson(Map json) { + if (json != null) { + code = json['code']; + type = json['type']; + message = json['message']; + } + } + int code; + String type; + String message; - ApiResponse({ - this.code, - this.type, - this.message, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is ApiResponse && + other.code == code && + other.type == type && + other.message == message; @override - String toString() { - return 'ApiResponse[code=$code, type=$type, message=$message, ]'; - } + int get hashCode => + code.hashCode + + type.hashCode + + message.hashCode; - ApiResponse.fromJson(Map json) { - if (json == null) return; - code = json['code']; - type = json['type']; - message = json['message']; - } + @override + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; Map toJson() { - Map json = {}; - if (code != null) + final json = {}; + if (code != null) { json['code'] = code; - if (type != null) + } + if (type != null) { json['type'] = type; - if (message != null) + } + if (message != null) { json['message'] = message; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => ApiResponse.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => ApiResponse.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = ApiResponse.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = ApiResponse.fromJson(v)); } return map; } // maps a json object with a list of ApiResponse-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = ApiResponse.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = ApiResponse.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/category.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/category.dart index 243b8855d352..500436027472 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/category.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/category.dart @@ -1,54 +1,79 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class Category { + /// Returns a new [Category] instance. + Category({ + this.id, + this.name, + }); + + /// Returns a new [Category] instance and optionally import its values from + /// [json] if it's non-null. + Category.fromJson(Map json) { + if (json != null) { + id = json['id']; + name = json['name']; + } + } + int id; + String name; - Category({ - this.id, - this.name, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is Category && + other.id == id && + other.name == name; @override - String toString() { - return 'Category[id=$id, name=$name, ]'; - } + int get hashCode => + id.hashCode + + name.hashCode; - Category.fromJson(Map json) { - if (json == null) return; - id = json['id']; - name = json['name']; - } + @override + String toString() => 'Category[id=$id, name=$name]'; Map toJson() { - Map json = {}; - if (id != null) + final json = {}; + if (id != null) { json['id'] = id; - if (name != null) + } + if (name != null) { json['name'] = name; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => Category.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => Category.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = Category.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = Category.fromJson(v)); } return map; } // maps a json object with a list of Category-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = Category.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = Category.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/order.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/order.dart index a5edbe07bc39..9de203f1feca 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/order.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/order.dart @@ -1,138 +1,201 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class Order { + /// Returns a new [Order] instance. + Order({ + this.id, + this.petId, + this.quantity, + this.shipDate, + this.status, + this.complete = false, + }); + + /// Returns a new [Order] instance and optionally import its values from + /// [json] if it's non-null. + Order.fromJson(Map json) { + if (json != null) { + id = json['id']; + petId = json['petId']; + quantity = json['quantity']; + shipDate = json['shipDate'] == null + ? null + : DateTime.parse(json['shipDate']); + status = OrderStatusEnum.fromJson(json['status']); + complete = json['complete']; + } + } + int id; + int petId; + int quantity; + DateTime shipDate; + /// Order Status OrderStatusEnum status; + - bool complete = false; + bool complete; - Order({ - this.id, - this.petId, - this.quantity, - this.shipDate, - this.status, - this.complete = false, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is Order && + other.id == id && + other.petId == petId && + other.quantity == quantity && + other.shipDate == shipDate && + other.status == status && + other.complete == complete; @override - String toString() { - return 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete, ]'; - } + int get hashCode => + id.hashCode + + petId.hashCode + + quantity.hashCode + + shipDate.hashCode + + status.hashCode + + complete.hashCode; - Order.fromJson(Map json) { - if (json == null) return; - id = json['id']; - petId = json['petId']; - quantity = json['quantity']; - shipDate = (json['shipDate'] == null) ? - null : - DateTime.parse(json['shipDate']); - status = OrderStatusEnum.fromJson(json['status']); - complete = json['complete']; - } + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Map toJson() { - Map json = {}; - if (id != null) + final json = {}; + if (id != null) { json['id'] = id; - if (petId != null) + } + if (petId != null) { json['petId'] = petId; - if (quantity != null) + } + if (quantity != null) { json['quantity'] = quantity; - if (shipDate != null) - json['shipDate'] = shipDate == null ? null : shipDate.toUtc().toIso8601String(); - if (status != null) - json['status'] = status.value; - if (complete != null) + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { json['complete'] = complete; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => Order.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => Order.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = Order.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = Order.fromJson(v)); } return map; } // maps a json object with a list of Order-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = Order.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = Order.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; } } + +/// Order Status class OrderStatusEnum { + /// Instantiate a new enum with the provided [value]. + const OrderStatusEnum._(this.value); + /// The underlying value of this enum member. final String value; - const OrderStatusEnum._internal(this.value); - - /// Order Status - static const OrderStatusEnum placed_ = OrderStatusEnum._internal("placed"); - /// Order Status - static const OrderStatusEnum approved_ = OrderStatusEnum._internal("approved"); - /// Order Status - static const OrderStatusEnum delivered_ = OrderStatusEnum._internal("delivered"); - - static List get values => const [ - placed_, - approved_, - delivered_, - ]; - - String toJson () { - return value; - } - @override - String toString () { - return value; - } + bool operator ==(Object other) => identical(this, other) || + other is OrderStatusEnum && other.value == value || + other is String && other == value; - static OrderStatusEnum fromJson(String value) { - return OrderStatusEnumTypeTransformer().decode(value); - } + @override + int get hashCode => toString().hashCode; - static List listFromJson(List json) { - return json == null - ? List() - : json.map((value) => OrderStatusEnum.fromJson(value)).toList(); - } + @override + String toString() => value; + + String toJson() => value; + + static const placed_ = OrderStatusEnum._('placed'); + static const approved_ = OrderStatusEnum._('approved'); + static const delivered_ = OrderStatusEnum._('delivered'); + + /// List of all possible values in this [enum][OrderStatusEnum]. + static const values = [ + placed_, + approved_, + delivered_, + ]; + + static OrderStatusEnum fromJson(String value) => + OrderStatusEnumTypeTransformer().decode(value); + + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json + .map((value) => OrderStatusEnum.fromJson(value)) + .toList(growable: true == growable); } +/// Transformation class that can [encode] an instance of [OrderStatusEnum] to String, +/// and [decode] dynamic data back to [OrderStatusEnum]. class OrderStatusEnumTypeTransformer { + const OrderStatusEnumTypeTransformer._(); - dynamic encode(OrderStatusEnum data) { - return data.value; - } + factory OrderStatusEnumTypeTransformer() => _instance ??= OrderStatusEnumTypeTransformer._(); - OrderStatusEnum decode(dynamic data) { + String encode(OrderStatusEnum data) => data.value; + + /// Decodes a [dynamic value][data] to a OrderStatusEnum. + /// + /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, + /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] + /// cannot be decoded successfully, then an [UnimplementedError] is thrown. + /// + /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, + /// and users are still using an old app with the old code. + OrderStatusEnum decode(dynamic data, {bool allowNull}) { switch (data) { - case "placed": return OrderStatusEnum.placed_; - case "approved": return OrderStatusEnum.approved_; - case "delivered": return OrderStatusEnum.delivered_; - default: return null; + case 'placed': return OrderStatusEnum.placed_; + case 'approved': return OrderStatusEnum.approved_; + case 'delivered': return OrderStatusEnum.delivered_; + default: + if (allowNull == false) { + throw ArgumentError('Unknown enum value to decode: $data'); + } } + return null; } -} + /// Singleton [OrderStatusEnumTypeTransformer] instance. + static OrderStatusEnumTypeTransformer _instance; +} diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart index b6ba84763567..cd77997466e7 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart @@ -1,142 +1,201 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class Pet { + /// Returns a new [Pet] instance. + Pet({ + this.id, + this.category, + @required this.name, + this.photoUrls = const [], + this.tags = const [], + this.status, + }); + + /// Returns a new [Pet] instance and optionally import its values from + /// [json] if it's non-null. + Pet.fromJson(Map json) { + if (json != null) { + id = json['id']; + category = Category.fromJson(json['category']); + name = json['name']; + photoUrls = json['photoUrls'] == null + ? null + : (json['photoUrls'] as List).cast(); + tags = Tag.listFromJson(json['tags']); + status = PetStatusEnum.fromJson(json['status']); + } + } + int id; + Category category; + String name; + - List photoUrls = const []; + List photoUrls; + - List tags = const []; + List tags; + /// pet status in the store PetStatusEnum status; - Pet({ - this.id, - this.category, - @required this.name, - @required this.photoUrls, - this.tags = const [], - this.status, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is Pet && + other.id == id && + other.category == category && + other.name == name && + other.photoUrls == photoUrls && + other.tags == tags && + other.status == status; @override - String toString() { - return 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status, ]'; - } + int get hashCode => + id.hashCode + + category.hashCode + + name.hashCode + + photoUrls.hashCode + + tags.hashCode + + status.hashCode; - Pet.fromJson(Map json) { - if (json == null) return; - id = json['id']; - category = (json['category'] == null) ? - null : - Category.fromJson(json['category']); - name = json['name']; - photoUrls = (json['photoUrls'] == null) ? - null : - (json['photoUrls'] as List).cast(); - tags = (json['tags'] == null) ? - null : - Tag.listFromJson(json['tags']); - status = PetStatusEnum.fromJson(json['status']); - } + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Map toJson() { - Map json = {}; - if (id != null) + final json = {}; + if (id != null) { json['id'] = id; - if (category != null) + } + if (category != null) { json['category'] = category; - if (name != null) + } + if (name != null) { json['name'] = name; - if (photoUrls != null) + } + if (photoUrls != null) { json['photoUrls'] = photoUrls; - if (tags != null) + } + if (tags != null) { json['tags'] = tags; - if (status != null) - json['status'] = status.value; + } + if (status != null) { + json['status'] = status; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => Pet.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => Pet.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = Pet.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = Pet.fromJson(v)); } return map; } // maps a json object with a list of Pet-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = Pet.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = Pet.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; } } + +/// pet status in the store class PetStatusEnum { + /// Instantiate a new enum with the provided [value]. + const PetStatusEnum._(this.value); + /// The underlying value of this enum member. final String value; - const PetStatusEnum._internal(this.value); - - /// pet status in the store - static const PetStatusEnum available_ = PetStatusEnum._internal("available"); - /// pet status in the store - static const PetStatusEnum pending_ = PetStatusEnum._internal("pending"); - /// pet status in the store - static const PetStatusEnum sold_ = PetStatusEnum._internal("sold"); - - static List get values => const [ - available_, - pending_, - sold_, - ]; - - String toJson () { - return value; - } - @override - String toString () { - return value; - } + bool operator ==(Object other) => identical(this, other) || + other is PetStatusEnum && other.value == value || + other is String && other == value; - static PetStatusEnum fromJson(String value) { - return PetStatusEnumTypeTransformer().decode(value); - } + @override + int get hashCode => toString().hashCode; - static List listFromJson(List json) { - return json == null - ? List() - : json.map((value) => PetStatusEnum.fromJson(value)).toList(); - } + @override + String toString() => value; + + String toJson() => value; + + static const available_ = PetStatusEnum._('available'); + static const pending_ = PetStatusEnum._('pending'); + static const sold_ = PetStatusEnum._('sold'); + + /// List of all possible values in this [enum][PetStatusEnum]. + static const values = [ + available_, + pending_, + sold_, + ]; + + static PetStatusEnum fromJson(String value) => + PetStatusEnumTypeTransformer().decode(value); + + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json + .map((value) => PetStatusEnum.fromJson(value)) + .toList(growable: true == growable); } +/// Transformation class that can [encode] an instance of [PetStatusEnum] to String, +/// and [decode] dynamic data back to [PetStatusEnum]. class PetStatusEnumTypeTransformer { + const PetStatusEnumTypeTransformer._(); - dynamic encode(PetStatusEnum data) { - return data.value; - } + factory PetStatusEnumTypeTransformer() => _instance ??= PetStatusEnumTypeTransformer._(); - PetStatusEnum decode(dynamic data) { + String encode(PetStatusEnum data) => data.value; + + /// Decodes a [dynamic value][data] to a PetStatusEnum. + /// + /// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully, + /// then null is returned. However, if [allowNull] is false and the [dynamic value][data] + /// cannot be decoded successfully, then an [UnimplementedError] is thrown. + /// + /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, + /// and users are still using an old app with the old code. + PetStatusEnum decode(dynamic data, {bool allowNull}) { switch (data) { - case "available": return PetStatusEnum.available_; - case "pending": return PetStatusEnum.pending_; - case "sold": return PetStatusEnum.sold_; - default: return null; + case 'available': return PetStatusEnum.available_; + case 'pending': return PetStatusEnum.pending_; + case 'sold': return PetStatusEnum.sold_; + default: + if (allowNull == false) { + throw ArgumentError('Unknown enum value to decode: $data'); + } } + return null; } -} + /// Singleton [PetStatusEnumTypeTransformer] instance. + static PetStatusEnumTypeTransformer _instance; +} diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart index 0907897e1c89..9533f955d44b 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart @@ -1,54 +1,79 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class Tag { + /// Returns a new [Tag] instance. + Tag({ + this.id, + this.name, + }); + + /// Returns a new [Tag] instance and optionally import its values from + /// [json] if it's non-null. + Tag.fromJson(Map json) { + if (json != null) { + id = json['id']; + name = json['name']; + } + } + int id; + String name; - Tag({ - this.id, - this.name, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is Tag && + other.id == id && + other.name == name; @override - String toString() { - return 'Tag[id=$id, name=$name, ]'; - } + int get hashCode => + id.hashCode + + name.hashCode; - Tag.fromJson(Map json) { - if (json == null) return; - id = json['id']; - name = json['name']; - } + @override + String toString() => 'Tag[id=$id, name=$name]'; Map toJson() { - Map json = {}; - if (id != null) + final json = {}; + if (id != null) { json['id'] = id; - if (name != null) + } + if (name != null) { json['name'] = name; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => Tag.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => Tag.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = Tag.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = Tag.fromJson(v)); } return map; } // maps a json object with a list of Tag-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = Tag.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = Tag.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; diff --git a/samples/client/petstore/dart2/petstore_client_lib/lib/model/user.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/model/user.dart index 29fb77ec9660..8c6290893963 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/model/user.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/model/user.dart @@ -1,90 +1,139 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// +// @dart=2.0 + +// ignore_for_file: unused_element, unused_import +// ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: lines_longer_than_80_chars + part of openapi.api; class User { + /// Returns a new [User] instance. + User({ + this.id, + this.username, + this.firstName, + this.lastName, + this.email, + this.password, + this.phone, + this.userStatus, + }); + + /// Returns a new [User] instance and optionally import its values from + /// [json] if it's non-null. + User.fromJson(Map json) { + if (json != null) { + id = json['id']; + username = json['username']; + firstName = json['firstName']; + lastName = json['lastName']; + email = json['email']; + password = json['password']; + phone = json['phone']; + userStatus = json['userStatus']; + } + } + int id; + String username; + String firstName; + String lastName; + String email; + String password; + String phone; + /// User Status int userStatus; - User({ - this.id, - this.username, - this.firstName, - this.lastName, - this.email, - this.password, - this.phone, - this.userStatus, - }); + @override + bool operator ==(Object other) => identical(this, other) || other is User && + other.id == id && + other.username == username && + other.firstName == firstName && + other.lastName == lastName && + other.email == email && + other.password == password && + other.phone == phone && + other.userStatus == userStatus; @override - String toString() { - return 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus, ]'; - } + int get hashCode => + id.hashCode + + username.hashCode + + firstName.hashCode + + lastName.hashCode + + email.hashCode + + password.hashCode + + phone.hashCode + + userStatus.hashCode; - User.fromJson(Map json) { - if (json == null) return; - id = json['id']; - username = json['username']; - firstName = json['firstName']; - lastName = json['lastName']; - email = json['email']; - password = json['password']; - phone = json['phone']; - userStatus = json['userStatus']; - } + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; Map toJson() { - Map json = {}; - if (id != null) + final json = {}; + if (id != null) { json['id'] = id; - if (username != null) + } + if (username != null) { json['username'] = username; - if (firstName != null) + } + if (firstName != null) { json['firstName'] = firstName; - if (lastName != null) + } + if (lastName != null) { json['lastName'] = lastName; - if (email != null) + } + if (email != null) { json['email'] = email; - if (password != null) + } + if (password != null) { json['password'] = password; - if (phone != null) + } + if (phone != null) { json['phone'] = phone; - if (userStatus != null) + } + if (userStatus != null) { json['userStatus'] = userStatus; + } return json; } - static List listFromJson(List json) { - return json == null ? List() : json.map((value) => User.fromJson(value)).toList(); - } + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => + json == null || json.isEmpty + ? true == emptyIsNull ? null : [] + : json.map((v) => User.fromJson(v)).toList(growable: true == growable); static Map mapFromJson(Map json) { - final map = Map(); + final map = {}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) => map[key] = User.fromJson(value)); + json.forEach((String key, dynamic v) => map[key] = User.fromJson(v)); } return map; } // maps a json object with a list of User-objects as value to a dart map - static Map> mapListFromJson(Map json) { - final map = Map>(); + static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { + final map = >{}; if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic value) { - map[key] = User.listFromJson(value); + json.forEach((String key, dynamic v) { + map[key] = User.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; diff --git a/samples/client/petstore/dart2/petstore_client_lib/pubspec.yaml b/samples/client/petstore/dart2/petstore_client_lib/pubspec.yaml index 49a6c58c4e70..78ba0e8da823 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/pubspec.yaml +++ b/samples/client/petstore/dart2/petstore_client_lib/pubspec.yaml @@ -1,14 +1,18 @@ -name: openapi -version: 1.0.0 -description: OpenAPI API client +# +# AUTO-GENERATED FILE, DO NOT MODIFY! +# + +name: 'openapi' +version: '1.0.0' +description: 'OpenAPI API client' authors: - - Author -homepage: homepage + - 'Author ' +homepage: 'homepage' environment: sdk: '>=2.0.0 <3.0.0' dependencies: http: '>=0.12.0 <0.13.0' - intl: ^0.16.1 - meta: ^1.1.8 + intl: '^0.16.1' + meta: '^1.1.8' dev_dependencies: - test: ^1.3.0 + test: '^1.3.0'