From 3af4527e1655e3bc3e36a4bcbfef6b8cd075e200 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sat, 3 Oct 2020 16:37:11 +0200 Subject: [PATCH 01/19] Updated Dart2 template. --- .../src/main/resources/dart2/api.mustache | 104 ++++---- .../main/resources/dart2/api_client.mustache | 245 +++++++++--------- .../src/main/resources/dart2/api_doc.mustache | 18 +- .../resources/dart2/api_exception.mustache | 12 +- .../main/resources/dart2/api_helper.mustache | 82 +++--- .../main/resources/dart2/api_test.mustache | 15 +- .../src/main/resources/dart2/apilib.mustache | 39 +-- .../dart2/auth/api_key_auth.mustache | 29 +-- .../dart2/auth/authentication.mustache | 9 +- .../main/resources/dart2/auth/header.mustache | 9 + .../dart2/auth/http_basic_auth.mustache | 16 +- .../dart2/auth/http_bearer_auth.mustache | 30 ++- .../main/resources/dart2/auth/oauth.mustache | 14 +- .../resources/dart2/auth/part_of.mustache | 1 + .../src/main/resources/dart2/class.mustache | 177 +++++++------ .../src/main/resources/dart2/enum.mustache | 106 +++++--- .../main/resources/dart2/enum_inline.mustache | 116 +++++---- .../src/main/resources/dart2/header.mustache | 9 + .../src/main/resources/dart2/model.mustache | 4 +- .../main/resources/dart2/model_test.mustache | 18 +- .../main/resources/dart2/object_doc.mustache | 6 +- .../src/main/resources/dart2/part_of.mustache | 1 + .../src/main/resources/dart2/pubspec.mustache | 20 +- .../src/main/resources/dart2/travis.mustache | 3 + 24 files changed, 596 insertions(+), 487 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/dart2/auth/header.mustache create mode 100644 modules/openapi-generator/src/main/resources/dart2/auth/part_of.mustache create mode 100644 modules/openapi-generator/src/main/resources/dart2/header.mustache create mode 100644 modules/openapi-generator/src/main/resources/dart2/part_of.mustache diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index ca638860499d..fee3acc0d206 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -1,31 +1,30 @@ -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 + + /// {{{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}}; + /// {{{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 {{#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}}; + String path = "{{{path}}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{{baseName}}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; // query params List queryParams = []; @@ -33,97 +32,100 @@ class {{classname}} { Map formParams = {}; {{#queryParams}} {{^required}} - if({{paramName}} != null) { + if ({{{paramName}}} != null) { {{/required}} - queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + queryParams.addAll(_convertParametersForCollectionFormat("{{{collectionFormat}}}", "{{{baseName}}}", {{{paramName}}})); {{^required}} } {{/required}} {{/queryParams}} {{#headerParams}} - headerParams["{{baseName}}"] = {{paramName}}; + headerParams["{{{baseName}}}"] = {{{paramName}}}; {{/headerParams}} List contentTypes = [{{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = [{{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + List authNames = [{{#authMethods}}"{{{name}}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest 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}}} /// {{#allParams}} - ///{{dataType}} {{paramName}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: + ///{{{dataType}}} {{{paramName}}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: /// {{#description}} {{{description}}}{{/description}} {{/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) { + /// {{{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 { + 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}}; + return {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), "{{{returnType}}}")); + {{/returnType}} {{/isMapContainer}} {{^isMapContainer}} {{#returnType}} - return apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as {{{returnType}}}; + return apiClient.deserialize(_decodeBodyBytes(response), "{{{returnType}}}") as {{{returnType}}}; {{/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..e7a05d02691e 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -1,142 +1,90 @@ -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}}}"}) { {{#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}} } + String basePath; + var client = Client(); + + final _defaultHeaderMap = {}; + final _authentications = {}; + void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - 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); - } - throw ApiException(500, 'Could not find a suitable class for deserialization'); - } - - dynamic deserialize(String json, String targetType) { + 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; + targetType = targetType.replaceAll(" ", ""); - 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)}'); + .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) { + if (body is MultipartRequest) { var request = MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); @@ -144,39 +92,96 @@ class ApiClient { 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); + } + + final msgBody = nullableContentType == "application/x-www-form-urlencoded" + ? formParams + : serialize(body); + final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; + + try { + switch(method.toUpperCase()) { + 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) { + var 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) { + var 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..8271793c37d8 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -1,16 +1,16 @@ -# {{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}}* 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}} @@ -24,7 +24,7 @@ Method | HTTP request | Description ### Example ```dart -import 'package:{{pubName}}/api.dart'; +import 'package:{{{pubName}}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} @@ -55,7 +55,7 @@ import 'package:{{pubName}}/api.dart'; {{/authMethods}} {{/hasAuthMethods}} -var api_instance = {{classname}}(); +var api_instance = {{{classname}}}(); {{#allParams}} var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} {{/allParams}} @@ -66,7 +66,7 @@ try { 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..45c92d7c07f2 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -1,15 +1,15 @@ -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"; 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..c281637288ab 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'); - +{{>header}} +{{>part_of}} // port from 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) { + return ""; + } + 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..676b4ce9ae14 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'; -import 'package:test/test.dart'; +{{>header}} +import "package:{{{pubName}}}/api.dart"; +import "package:test/test.dart"; {{#operations}} -/// tests for {{classname}} +/// tests for {{{classname}}} void main() { - var instance = {{classname}}(); + var 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..ce6cdbbdfc6e 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -1,23 +1,30 @@ -library {{pubName}}.api; +{{>header}} +{{#pubLibrary}}library {{{pubLibrary}}};{{/pubLibrary}}{{^pubLibrary}}library {{{pubName}}}.api;{{/pubLibrary}} -import 'dart:async'; -import 'dart:convert'; -import 'package:http/http.dart'; -import 'package:intl/intl.dart'; -import 'package:meta/meta.dart'; +import "dart:async"; +import "dart:convert"; +import "dart:io"; -part 'api_client.dart'; -part 'api_helper.dart'; -part 'api_exception.dart'; -part 'auth/authentication.dart'; -part 'auth/api_key_auth.dart'; -part 'auth/oauth.dart'; -part 'auth/http_basic_auth.dart'; -part 'auth/http_bearer_auth.dart'; +import "package:http/http.dart"; +import "package:intl/intl.dart"; +import "package:meta/meta.dart"; -{{#apiInfo}}{{#apis}}part 'api/{{classFilename}}.dart'; +part "api_client.dart"; +part "api_helper.dart"; +part "api_exception.dart"; +part "auth/authentication.dart"; +part "auth/api_key_auth.dart"; +part "auth/oauth.dart"; +part "auth/http_basic_auth.dart"; +part "auth/http_bearer_auth.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": "|"}; +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..fa3268fdcf3d 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,33 +1,26 @@ -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) { + if (location == "query" && value != null) { queryParams.add(QueryParam(paramName, value)); - } else if (location == 'header' && value != null) { + } else if (location == "header" && value != null) { headerParams[paramName] = value; - } else if (location == 'cookie' && value != null) { - headerParams.update('Cookie', (String existingCookie) { + } else if (location == "cookie" && value != null) { + headerParams.update("Cookie", (String existingCookie) { return "$existingCookie; $paramName=$value"; - }, ifAbsent: () => '$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..cc03395da8de --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache @@ -0,0 +1,9 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes 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..3292ba6ab34b 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 str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic ${base64.encode(utf8.encode(str))}"; } - - 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..dd99aa73041a 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..3b004d3c1925 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..4bcf0a0331aa 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -1,105 +1,134 @@ -class {{classname}} { +class {{{classname}}} { + {{{classname}}}({ + {{#vars}} + {{#isNullable}}{{#required}}@required {{/required}}this.{{{name}}},{{/isNullable}}{{^isNullable}}{{#defaultValue}}this.{{{name}}} = {{#isContainer}}const {{/isContainer}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{#required}}@required {{/required}}this.{{{name}}}{{/defaultValue}},{{/isNullable}} + {{/vars}} + }); + {{#vars}} {{#description}}/// {{{description}}}{{/description}} {{^isEnum}} - {{^defaultValue}}{{{dataType}}} {{name}};{{/defaultValue}}{{#defaultValue}}{{{dataType}}} {{name}} = {{defaultValue}};{{/defaultValue}} + {{{dataType}}} {{{name}}}; {{/isEnum}} {{#isEnum}} - {{#allowableValues}} - {{#min}} // range from {{min}} to {{max}}{{/min}}{{classname}}{{{enumName}}} {{name}}{{#required}} = {{classname}}{{{enumName}}}._internal({{{defaultValue}}}){{/required}}{{^required}}{{/required}}; - {{/allowableValues}} + {{#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}} - {{classname}}({ + @override + int get hashCode => {{#vars}} - {{#required}}@required this.{{name}}{{/required}}{{^required}}this.{{name}}{{#defaultValue}} = {{defaultValue}}{{/defaultValue}}{{/required}}, + {{#isNullable}}({{{name}}}?.hashCode ?? 0){{/isNullable}}{{^isNullable}}{{{name}}}.hashCode{{/isNullable}}{{^-last}} +{{/-last}}{{#-last}};{{/-last}} {{/vars}} - }); @override - String toString() { - return '{{classname}}[{{#vars}}{{name}}=${{name}}, {{/vars}}]'; - } + String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; - {{classname}}.fromJson(Map json) { - if (json == null) return; + {{{classname}}}.fromJson(Map json) { + if (json == null) { + return; + } {{#vars}} {{#isDateTime}} - {{name}} = (json['{{baseName}}'] == null) ? + {{{name}}} = json["{{{baseName}}}"] == null ? null : - DateTime.parse(json['{{baseName}}']); + DateTime.parse(json["{{{baseName}}}"]); {{/isDateTime}} {{#isDate}} - {{name}} = (json['{{baseName}}'] == null) ? + {{{name}}} = json["{{{baseName}}}"] == null ? null : - DateTime.parse(json['{{baseName}}']); + DateTime.parse(json["{{{baseName}}}"]); {{/isDate}} {{^isDateTime}} {{^isDate}} {{#complexType}} {{#isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : {{#items.isListContainer}} - (json['{{baseName}}'] as List).map( - (e) => e == null ? null : + {{{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(); + ).toList(growable: false); {{/items.isListContainer}} {{^items.isListContainer}} - {{complexType}}.listFromJson(json['{{baseName}}']); + {{{name}}} = {{{complexType}}}.listFromJson(json["{{{baseName}}}"]); {{/items.isListContainer}} {{/isListContainer}} {{^isListContainer}} {{#isMapContainer}} {{#items.isListContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{items.complexType}}.mapListFromJson(json['{{baseName}}']); + {{{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}}']); + {{{name}}} = json["{{{baseName}}}"] == null + ? null + : {{{complexType}}}.mapFromJson(json["{{{baseName}}}"]); {{/items.isListContainer}} {{/isMapContainer}} {{^isMapContainer}} - {{name}} = (json['{{baseName}}'] == null) ? - null : - {{complexType}}.fromJson(json['{{baseName}}']); + {{{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) ? + {{{name}}} = json["{{{baseName}}}"] == null ? null : - (json['{{baseName}}'] as Map).cast(); + (json["{{{baseName}}}"] as Map).cast(); {{/isMapContainer}} {{^isMapContainer}} {{#isNumber}} - {{name}} = (json['{{baseName}}'] == null) ? + {{{name}}} = json["{{{baseName}}}"] == null ? null : - json['{{baseName}}'].toDouble(); + 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}} @@ -111,49 +140,44 @@ class {{classname}} { } 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}} + json["{{{baseName}}}"] = {{{name}}}.toUtc().toIso8601String(); + {{/isDateTime}} + {{#isDate}} + json["{{{baseName}}}"] = _dateFormatter.format({{{name}}}.toUtc()); + {{/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 +185,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..84f40c220531 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum.mustache @@ -1,60 +1,88 @@ -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 (false == allowNull) { + 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..031a496a7a83 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,88 @@ -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 (false == allowNull) { + 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..cc03395da8de --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/header.mustache @@ -0,0 +1,9 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes 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..a468b4838062 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:test/test.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}} + var 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..81bb29ce4767 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 From 4270565502636f89c97ee5581cd59534ff095fee Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sat, 3 Oct 2020 16:40:07 +0200 Subject: [PATCH 02/19] Generated Petstore client code for Dart2. --- .../dart2/petstore_client_lib/.travis.yml | 3 + .../dart2/petstore_client_lib/doc/Pet.md | 4 +- .../dart2/petstore_client_lib/lib/api.dart | 66 ++-- .../petstore_client_lib/lib/api/pet_api.dart | 369 ++++++++++-------- .../lib/api/store_api.dart | 185 ++++----- .../petstore_client_lib/lib/api/user_api.dart | 338 ++++++++-------- .../petstore_client_lib/lib/api_client.dart | 247 ++++++------ .../lib/api_exception.dart | 18 +- .../petstore_client_lib/lib/api_helper.dart | 81 ++-- .../lib/auth/api_key_auth.dart | 35 +- .../lib/auth/authentication.dart | 15 +- .../lib/auth/http_basic_auth.dart | 22 +- .../lib/auth/http_bearer_auth.dart | 38 +- .../petstore_client_lib/lib/auth/oauth.dart | 20 +- .../lib/model/api_response.dart | 84 ++-- .../lib/model/category.dart | 72 ++-- .../petstore_client_lib/lib/model/order.dart | 219 +++++++---- .../petstore_client_lib/lib/model/pet.dart | 227 +++++++---- .../petstore_client_lib/lib/model/tag.dart | 72 ++-- .../petstore_client_lib/lib/model/user.dart | 144 ++++--- .../dart2/petstore_client_lib/pubspec.yaml | 20 +- 21 files changed, 1334 insertions(+), 945 deletions(-) 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/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/lib/api.dart b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart index baf59a69c137..ecc2e38b4723 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -1,30 +1,46 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + library openapi.api; -import 'dart:async'; -import 'dart:convert'; -import 'package:http/http.dart'; -import 'package:intl/intl.dart'; -import 'package:meta/meta.dart'; - -part 'api_client.dart'; -part 'api_helper.dart'; -part 'api_exception.dart'; -part 'auth/authentication.dart'; -part 'auth/api_key_auth.dart'; -part 'auth/oauth.dart'; -part 'auth/http_basic_auth.dart'; -part 'auth/http_bearer_auth.dart'; - -part 'api/pet_api.dart'; -part 'api/store_api.dart'; -part 'api/user_api.dart'; - -part 'model/api_response.dart'; -part 'model/category.dart'; -part 'model/order.dart'; -part 'model/pet.dart'; -part 'model/tag.dart'; -part 'model/user.dart'; +import "dart:async"; +import "dart:convert"; +import "dart:io"; + +import "package:http/http.dart"; +import "package:intl/intl.dart"; +import "package:meta/meta.dart"; + +part "api_client.dart"; +part "api_helper.dart"; +part "api_exception.dart"; +part "auth/authentication.dart"; +part "auth/api_key_auth.dart"; +part "auth/oauth.dart"; +part "auth/http_basic_auth.dart"; +part "auth/http_bearer_auth.dart"; + +part "api/pet_api.dart"; +part "api/store_api.dart"; +part "api/user_api.dart"; + +part "model/api_response.dart"; +part "model/category.dart"; +part "model/order.dart"; +part "model/pet.dart"; +part "model/tag.dart"; +part "model/user.dart"; +const _delimiters = {"csv": ",", "ssv": " ", "tsv": "\t", "pipes": "|"}; +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..5712a709aa54 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,12 +1,21 @@ -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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes +part of openapi.api; -class PetApi { - final ApiClient apiClient; +class PetApi { PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + final ApiClient apiClient; + /// Add a new pet to the store with HTTP info returned /// /// @@ -14,7 +23,7 @@ class PetApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -31,24 +40,25 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -57,13 +67,13 @@ class PetApi { /// 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 @@ -73,7 +83,7 @@ class PetApi { Object postBody; // verify required params are set - if(petId == null) { + if (petId == null) { throw ApiException(400, "Missing required param: petId"); } @@ -91,24 +101,25 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -119,13 +130,13 @@ class PetApi { /// /// 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 @@ -135,7 +146,7 @@ class PetApi { Object postBody; // verify required params are set - if(status == null) { + if (status == null) { throw ApiException(400, "Missing required param: status"); } @@ -153,40 +164,43 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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): + ///List status (required): /// Status values that need to be considered for filter /// Multiple status values can be provided with comma separated strings 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 @@ -196,7 +210,7 @@ class PetApi { Object postBody; // verify required params are set - if(tags == null) { + if (tags == null) { throw ApiException(400, "Missing required param: tags"); } @@ -214,40 +228,43 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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): + ///List tags (required): /// Tags to filter by /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. 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 @@ -257,7 +274,7 @@ class PetApi { Object postBody; // verify required params are set - if(petId == null) { + if (petId == null) { throw ApiException(400, "Missing required param: petId"); } @@ -274,24 +291,25 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["api_key"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -300,14 +318,14 @@ class PetApi { /// ID of pet to return /// Returns a single pet 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "Pet") as Pet; + } + return null; } /// Update an existing pet with HTTP info returned @@ -317,7 +335,7 @@ class PetApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -334,24 +352,25 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -360,13 +379,13 @@ class PetApi { /// 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 @@ -376,7 +395,7 @@ class PetApi { Object postBody; // verify required params are set - if(petId == null) { + if (petId == null) { throw ApiException(400, "Missing required param: petId"); } @@ -393,36 +412,39 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); if (name != null) { hasFields = true; - mp.fields['name'] = parameterToString(name); + mp.fields["name"] = parameterToString(name); } if (status != null) { hasFields = true; - mp.fields['status'] = parameterToString(status); + mp.fields["status"] = parameterToString(status); } - if(hasFields) + if (hasFields) { postBody = mp; + } + } else { + if (name != null) { + formParams["name"] = parameterToString(name); + } + if (status != null) { + formParams["status"] = parameterToString(status); + } } - else { - if (name != null) - formParams['name'] = parameterToString(name); - 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 @@ -435,13 +457,13 @@ class PetApi { /// 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 @@ -451,7 +473,7 @@ class PetApi { Object postBody; // verify required params are set - if(petId == null) { + if (petId == null) { throw ApiException(400, "Missing required param: petId"); } @@ -468,35 +490,37 @@ class PetApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["petstore_auth"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); if (additionalMetadata != null) { hasFields = true; - mp.fields['additionalMetadata'] = parameterToString(additionalMetadata); + mp.fields["additionalMetadata"] = parameterToString(additionalMetadata); } if (file != null) { hasFields = true; - mp.fields['file'] = file.field; + mp.fields["file"] = file.field; mp.files.add(file); } - if(hasFields) + if (hasFields) { postBody = mp; - } - else { - if (additionalMetadata != null) - formParams['additionalMetadata'] = parameterToString(additionalMetadata); + } + } 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 @@ -509,14 +533,13 @@ class PetApi { /// 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "ApiResponse") as ApiResponse; + } + 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..2f6b1cd7e338 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,20 +1,29 @@ -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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes +part of openapi.api; -class StoreApi { - final ApiClient apiClient; +class StoreApi { StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + final ApiClient apiClient; + /// Delete purchase order by ID with HTTP info returned /// - /// 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 Future deleteOrderWithHttpInfo(String orderId) async { Object postBody; // verify required params are set - if(orderId == null) { + if (orderId == null) { throw ApiException(400, "Missing required param: orderId"); } @@ -31,39 +40,40 @@ class StoreApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 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 @@ -87,49 +97,49 @@ class StoreApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = ["api_key"]; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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) { - return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); - ; - } else { - return null; } + if (response.body != null) { + return Map.from(apiClient.deserialize(_decodeBodyBytes(response), "Map")); + } + return null; } /// Find purchase order by ID with HTTP info returned /// - /// 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 Future getOrderByIdWithHttpInfo(int orderId) async { Object postBody; // verify required params are set - if(orderId == null) { + if (orderId == null) { throw ApiException(400, "Missing required param: orderId"); } @@ -146,40 +156,41 @@ class StoreApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "Order") as Order; + } + return null; } /// Place an order for a pet with HTTP info returned @@ -189,7 +200,7 @@ class StoreApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -206,24 +217,25 @@ class StoreApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -232,14 +244,13 @@ class StoreApi { /// 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "Order") as Order; + } + 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..290357ddc8e0 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,12 +1,21 @@ -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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes +part of openapi.api; -class UserApi { - final ApiClient apiClient; +class UserApi { UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + final ApiClient apiClient; + /// Create user with HTTP info returned /// /// This can only be done by the logged in user. @@ -14,7 +23,7 @@ class UserApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -31,24 +40,25 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -57,13 +67,13 @@ class UserApi { /// Created user object /// This can only be done by the logged in user. 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 @@ -73,7 +83,7 @@ class UserApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -90,39 +100,40 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 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 @@ -132,7 +143,7 @@ class UserApi { Object postBody = body; // verify required params are set - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -149,39 +160,40 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 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 @@ -191,7 +203,7 @@ class UserApi { Object postBody; // verify required params are set - if(username == null) { + if (username == null) { throw ApiException(400, "Missing required param: username"); } @@ -208,24 +220,25 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -234,13 +247,13 @@ class UserApi { /// The name that needs to be deleted /// This can only be done by the logged in user. 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 @@ -250,7 +263,7 @@ class UserApi { Object postBody; // verify required params are set - if(username == null) { + if (username == null) { throw ApiException(400, "Missing required param: username"); } @@ -267,24 +280,25 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -293,14 +307,14 @@ class UserApi { /// 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "User") as User; + } + return null; } /// Logs user into the system with HTTP info returned @@ -310,10 +324,10 @@ class UserApi { Object postBody; // verify required params are set - if(username == null) { + if (username == null) { throw ApiException(400, "Missing required param: username"); } - if(password == null) { + if (password == null) { throw ApiException(400, "Missing required param: password"); } @@ -332,24 +346,25 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -360,14 +375,14 @@ class UserApi { /// 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) { - return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; - } else { - return null; } + if (response.body != null) { + return apiClient.deserialize(_decodeBodyBytes(response), "String") as String; + } + return null; } /// Logs out current logged in user session with HTTP info returned @@ -391,37 +406,38 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -431,10 +447,10 @@ class UserApi { Object postBody = body; // verify required params are set - if(username == null) { + if (username == null) { throw ApiException(400, "Missing required param: username"); } - if(body == null) { + if (body == null) { throw ApiException(400, "Missing required param: body"); } @@ -451,24 +467,25 @@ class UserApi { String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = []; - if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); - if(hasFields) + 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 @@ -479,13 +496,12 @@ class UserApi { /// Updated user object /// This can only be done by the logged in user. 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..d31f9cc668ab 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,127 +1,84 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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(); - Map _defaultHeaderMap = {}; - Map _authentications = {}; - - final _regList = RegExp(r'^List<(.*)>$'); - final _regMap = RegExp(r'^Map$'); - - 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(); - } + final _defaultHeaderMap = {}; + final _authentications = {}; void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - 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'); - case 'ApiResponse': - return ApiResponse.fromJson(value); - case 'Category': - return Category.fromJson(value); - case 'Order': - return Order.fromJson(value); - case 'Pet': - return Pet.fromJson(value); - case 'Tag': - return Tag.fromJson(value); - 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))); - } - } - } - } 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'); - } - - dynamic deserialize(String json, String targetType) { + 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; + targetType = targetType.replaceAll(" ", ""); - 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)}'); + .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) { + if (body is MultipartRequest) { var request = MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); @@ -129,39 +86,97 @@ class ApiClient { 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); + } + + final msgBody = nullableContentType == "application/x-www-form-urlencoded" + ? formParams + : serialize(body); + final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; + + try { + switch(method.toUpperCase()) { + 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"); + case "ApiResponse": + return ApiResponse.fromJson(value); + case "Category": + return Category.fromJson(value); + case "Order": + return Order.fromJson(value); + case "Pet": + return Pet.fromJson(value); + case "Tag": + return Tag.fromJson(value); + case "User": + return User.fromJson(value); default: - return client.get(url, headers: nullableHeaderParams); + Match match; + if (value is List && (match = _regList.firstMatch(targetType)) != null) { + var 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) { + var 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/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..4b5cca36c93f 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,15 +1,25 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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"; 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..4cea344ec792 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,62 @@ -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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes -const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; -var _dateFormatter = DateFormat('yyyy-MM-dd'); +part of openapi.api; // port from 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) { + return ""; + } + 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..67b9fd51c8c6 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,33 +1,36 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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) { + if (location == "query" && value != null) { queryParams.add(QueryParam(paramName, value)); - } else if (location == 'header' && value != null) { + } else if (location == "header" && value != null) { headerParams[paramName] = value; - } else if (location == 'cookie' && value != null) { - headerParams.update('Cookie', (String existingCookie) { + } else if (location == "cookie" && value != null) { + headerParams.update("Cookie", (String existingCookie) { return "$existingCookie; $paramName=$value"; - }, ifAbsent: () => '$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..b4110d0d7e5a 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,16 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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..592d40d289fc 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,22 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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 str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic ${base64.encode(utf8.encode(str))}"; } - - 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..f91e57a8ca0d 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,39 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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..f8923130f7bc 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,24 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + 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..b8c6e5c7c22c 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,88 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class ApiResponse { + ApiResponse({ + this.code, + this.type, + this.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; + + @override + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; ApiResponse.fromJson(Map json) { - if (json == null) return; - code = json['code']; - type = json['type']; - message = json['message']; + if (json == null) { + return; + } + code = json["code"]; + type = json["type"]; + message = json["message"]; } Map toJson() { - Map json = {}; - if (code != null) - json['code'] = code; - if (type != null) - json['type'] = type; - if (message != null) - json['message'] = message; + final json = {}; + if (code != null) { + json["code"] = code; + } + if (type != null) { + json["type"] = type; + } + 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..c5f3ae8b9da6 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,78 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class Category { + Category({ + this.id, + this.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; + + @override + String toString() => 'Category[id=$id, name=$name]'; Category.fromJson(Map json) { - if (json == null) return; - id = json['id']; - name = json['name']; + if (json == null) { + return; + } + id = json["id"]; + name = json["name"]; } Map toJson() { - Map json = {}; - if (id != null) - json['id'] = id; - if (name != null) - json['name'] = name; + final json = {}; + if (id != null) { + json["id"] = id; + } + 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..2950c4456bcc 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class Order { + Order({ + this.id, + this.petId, + this.quantity, + this.shipDate, + this.status, + this.complete = false, + }); + 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; + + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Order.fromJson(Map json) { - if (json == null) return; - id = json['id']; - petId = json['petId']; - quantity = json['quantity']; - shipDate = (json['shipDate'] == null) ? + 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']; + DateTime.parse(json["shipDate"]); + status = OrderStatusEnum.fromJson(json["status"]); + complete = json["complete"]; } Map toJson() { - Map json = {}; - if (id != null) - json['id'] = id; - if (petId != null) - json['petId'] = petId; - 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) - json['complete'] = complete; + final json = {}; + if (id != null) { + json["id"] = id; + } + if (petId != null) { + json["petId"] = petId; + } + if (quantity != null) { + json["quantity"] = quantity; + } + 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; + default: + if (false == allowNull) { + 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..06a16c04ff0b 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class Pet { + Pet({ + this.id, + this.category, + @required this.name, + this.photoUrls = const const [], + this.tags = const const [], + this.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; + + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; 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']); + if (json == null) { + return; + } + 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"]); } Map toJson() { - Map json = {}; - if (id != null) - json['id'] = id; - if (category != null) - json['category'] = category; - if (name != null) - json['name'] = name; - if (photoUrls != null) - json['photoUrls'] = photoUrls; - if (tags != null) - json['tags'] = tags; - if (status != null) - json['status'] = status.value; + final json = {}; + if (id != null) { + json["id"] = id; + } + if (category != null) { + json["category"] = category; + } + if (name != null) { + json["name"] = name; + } + if (photoUrls != null) { + json["photoUrls"] = photoUrls; + } + if (tags != null) { + json["tags"] = tags; + } + 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; + default: + if (false == allowNull) { + 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..4336ea79cdc3 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,78 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class Tag { + Tag({ + this.id, + this.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; + + @override + String toString() => 'Tag[id=$id, name=$name]'; Tag.fromJson(Map json) { - if (json == null) return; - id = json['id']; - name = json['name']; + if (json == null) { + return; + } + id = json["id"]; + name = json["name"]; } Map toJson() { - Map json = {}; - if (id != null) - json['id'] = id; - if (name != null) - json['name'] = name; + final json = {}; + if (id != null) { + json["id"] = id; + } + 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..17553d3b666a 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,138 @@ +// +// 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: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: prefer_single_quotes + part of openapi.api; class User { + User({ + this.id, + this.username, + this.firstName, + this.lastName, + this.email, + this.password, + this.phone, + this.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; + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; 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']; + 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"]; } Map toJson() { - Map json = {}; - if (id != null) - json['id'] = id; - if (username != null) - json['username'] = username; - if (firstName != null) - json['firstName'] = firstName; - if (lastName != null) - json['lastName'] = lastName; - if (email != null) - json['email'] = email; - if (password != null) - json['password'] = password; - if (phone != null) - json['phone'] = phone; - if (userStatus != null) - json['userStatus'] = userStatus; + final json = {}; + if (id != null) { + json["id"] = id; + } + if (username != null) { + json["username"] = username; + } + if (firstName != null) { + json["firstName"] = firstName; + } + if (lastName != null) { + json["lastName"] = lastName; + } + if (email != null) { + json["email"] = email; + } + if (password != null) { + json["password"] = password; + } + if (phone != null) { + json["phone"] = phone; + } + 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' From 23491508584b376ea8881490a23e2710dce11af0 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 00:54:14 +0200 Subject: [PATCH 03/19] Use double-quotes instead of single-quotes, to be consistent with output of Dart generator. --- .../src/main/resources/dart2/README.mustache | 16 ++++++++-------- .../main/resources/dart2/api_client.mustache | 10 +++++----- .../src/main/resources/dart2/api_doc.mustache | 18 +++++++++--------- .../src/main/resources/dart2/class.mustache | 2 +- .../src/main/resources/dart2/enum.mustache | 5 ++--- .../main/resources/dart2/enum_inline.mustache | 5 ++--- .../main/resources/dart2/object_doc.mustache | 2 +- 7 files changed, 28 insertions(+), 30 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index a16cba3d5fa2..593b713ab375 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -48,34 +48,34 @@ 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}} {{#isBasic}} {{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' -//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; +//defaultApiClient.getAuthentication("{{{name}}}").username = "YOUR_USERNAME" +//defaultApiClient.getAuthentication("{{{name}}}").password = "YOUR_PASSWORD"; {{/isBasicBasic}} {{#isBasicBearer}} // TODO Configure HTTP Bearer authorization: {{{name}}} // Case 1. Use String Token -//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); +//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken("YOUR_ACCESS_TOKEN"); // Case 2. Use Function which generate token. // String yourTokenGeneratorFunction() { ... } -//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); +//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken(yourTokenGeneratorFunction); {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication("{{{name}}}").apiKey = "YOUR_API_KEY"; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; +//defaultApiClient.getAuthentication("{{{name}}}").apiKeyPrefix = "Bearer"; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("{{{name}}}").accessToken = "YOUR_ACCESS_TOKEN"; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} 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 e7a05d02691e..01ecbbfe2bf7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -100,7 +100,7 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; try { - switch(method.toUpperCase()) { + 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); @@ -109,13 +109,13 @@ class ApiClient { 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); + 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); + 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); + 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.withInner(400, "Exception occurred: $method $path", e, trace); } throw ApiException(400, "Invalid HTTP operation: $method $path"); 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 8271793c37d8..91f670d7bd8e 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -3,7 +3,7 @@ ## Load the API package ```dart -import 'package:{{{pubName}}}/api.dart'; +import "package:{{{pubName}}}/api.dart"; ``` All URIs are relative to *{{basePath}}* @@ -24,33 +24,33 @@ Method | HTTP request | Description ### Example ```dart -import 'package:{{{pubName}}}/api.dart'; +import "package:{{{pubName}}}/api.dart"; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} {{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' -//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; +//defaultApiClient.getAuthentication("{{{name}}}").username = "YOUR_USERNAME" +//defaultApiClient.getAuthentication("{{{name}}}").password = "YOUR_PASSWORD"; {{/isBasicBasic}} {{#isBasicBearer}} // TODO Configure HTTP Bearer authorization: {{{name}}} // Case 1. Use String Token -//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); +//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken("YOUR_ACCESS_TOKEN"); // Case 2. Use Function which generate token. // String yourTokenGeneratorFunction() { ... } -//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); +//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken(yourTokenGeneratorFunction); {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication("{{{name}}}").apiKey = "YOUR_API_KEY"; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; +//defaultApiClient.getAuthentication("{{{name}}}").apiKeyPrefix = "Bearer"; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("{{{name}}}").accessToken = "YOUR_ACCESS_TOKEN"; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index 4bcf0a0331aa..80d77d59b374 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -40,7 +40,7 @@ class {{{classname}}} { {{/vars}} @override - String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; + String toString() => "{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]"; {{{classname}}}.fromJson(Map json) { if (json == null) { diff --git a/modules/openapi-generator/src/main/resources/dart2/enum.mustache b/modules/openapi-generator/src/main/resources/dart2/enum.mustache index 84f40c220531..09a0008ed077 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum.mustache @@ -12,8 +12,7 @@ class {{{classname}}} { {{/isEnum}} @override - bool operator ==(Object other) => - identical(this, other) || + bool operator ==(Object other) => identical(this, other) || other is {{{classname}}} && other.value == value || other is {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} && other == value; @@ -76,7 +75,7 @@ class {{{classname}}}TypeTransformer { {{/enumVars}} {{/allowableValues}} default: - if (false == allowNull) { + if (allowNull == false) { throw ArgumentError("Unknown enum value to decode: $data"); } } 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 031a496a7a83..9408b2fcf96d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache @@ -12,8 +12,7 @@ class {{{classname}}}{{{enumName}}} { {{/isEnum}} @override - bool operator ==(Object other) => - identical(this, other) || + bool operator ==(Object other) => identical(this, other) || other is {{{classname}}}{{{enumName}}} && other.value == value || other is {{#isEnum}}String{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} && other == value; @@ -76,7 +75,7 @@ class {{{classname}}}{{{enumName}}}TypeTransformer { {{/enumVars}} {{/allowableValues}} default: - if (false == allowNull) { + if (allowNull == false) { throw ArgumentError("Unknown enum value to decode: $data"); } } 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 81bb29ce4767..fcc2f4c8f268 100644 --- a/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:{{{pubName}}}/api.dart'; +import "package:{{{pubName}}}/api.dart"; ``` ## Properties From c28af2199bcad1b9c998f711800df8a04f08835d Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 00:56:30 +0200 Subject: [PATCH 04/19] Updated Petstore samples. --- .../dart2/petstore_client_lib/README.md | 4 +-- .../petstore_client_lib/doc/ApiResponse.md | 2 +- .../dart2/petstore_client_lib/doc/Category.md | 2 +- .../dart2/petstore_client_lib/doc/Order.md | 2 +- .../dart2/petstore_client_lib/doc/Pet.md | 2 +- .../dart2/petstore_client_lib/doc/PetApi.md | 36 +++++++++---------- .../dart2/petstore_client_lib/doc/StoreApi.md | 14 ++++---- .../dart2/petstore_client_lib/doc/Tag.md | 2 +- .../dart2/petstore_client_lib/doc/User.md | 2 +- .../dart2/petstore_client_lib/doc/UserApi.md | 18 +++++----- .../petstore_client_lib/lib/api_client.dart | 10 +++--- .../lib/model/api_response.dart | 2 +- .../lib/model/category.dart | 2 +- .../petstore_client_lib/lib/model/order.dart | 7 ++-- .../petstore_client_lib/lib/model/pet.dart | 7 ++-- .../petstore_client_lib/lib/model/tag.dart | 2 +- .../petstore_client_lib/lib/model/user.dart | 2 +- 17 files changed, 57 insertions(+), 59 deletions(-) diff --git a/samples/client/petstore/dart2/petstore_client_lib/README.md b/samples/client/petstore/dart2/petstore_client_lib/README.md index 1cf4ca28f0a8..877b0e588576 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/README.md +++ b/samples/client/petstore/dart2/petstore_client_lib/README.md @@ -37,10 +37,10 @@ TODO Please follow the [installation procedure](#installation--usage) and then run the following: ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//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 diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md b/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md index 7ad5da0f89e4..f6b10db5d194 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md index 98d0b14be7b1..ffb7df6a5391 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md index bde5ffe51a2c..358ee59fcb15 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties 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 88512ee37035..4277e35a2488 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties 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..69a4c0b4d823 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -26,9 +26,9 @@ Add a new pet to the store ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//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 @@ -68,9 +68,9 @@ Deletes a pet ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; var api_instance = PetApi(); var petId = 789; // int | Pet id to delete @@ -114,9 +114,9 @@ Multiple status values can be provided with comma separated strings ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; var api_instance = PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -159,9 +159,9 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; var api_instance = PetApi(); var tags = []; // List | Tags to filter by @@ -204,11 +204,11 @@ Returns a single pet ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure API key authorization: api_key -//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication("api_key").apiKey = "YOUR_API_KEY"; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; +//defaultApiClient.getAuthentication("api_key").apiKeyPrefix = "Bearer"; var api_instance = PetApi(); var petId = 789; // int | ID of pet to return @@ -249,9 +249,9 @@ Update an existing pet ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//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 @@ -291,9 +291,9 @@ Updates a pet in the store with form data ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; var api_instance = PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -337,9 +337,9 @@ uploads an image ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; var api_instance = PetApi(); var petId = 789; // int | ID of pet to update 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..cce6c734a169 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,7 +24,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = StoreApi(); var orderId = orderId_example; // String | ID of the order that needs to be deleted @@ -66,11 +66,11 @@ Returns a map of status codes to quantities ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; // TODO Configure API key authorization: api_key -//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication("api_key").apiKey = "YOUR_API_KEY"; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; +//defaultApiClient.getAuthentication("api_key").apiKeyPrefix = "Bearer"; var api_instance = StoreApi(); @@ -109,7 +109,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = StoreApi(); var orderId = 789; // int | ID of pet that needs to be fetched @@ -150,7 +150,7 @@ Place an order for a pet ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = StoreApi(); var body = Order(); // Order | order placed for purchasing the pet diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md index c219f987c19c..a939b901f173 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/User.md b/samples/client/petstore/dart2/petstore_client_lib/doc/User.md index fa87e64d8595..0a3686642a8f 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/User.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/User.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` ## Properties 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..7b102ca0d91d 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -28,7 +28,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var body = User(); // User | Created user object @@ -68,7 +68,7 @@ Creates list of users with given input array ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var body = [List<User>()]; // List | List of user object @@ -108,7 +108,7 @@ Creates list of users with given input array ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var body = [List<User>()]; // List | List of user object @@ -150,7 +150,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var username = username_example; // String | The name that needs to be deleted @@ -190,7 +190,7 @@ Get user by user name ### Example ```dart -import 'package:openapi/api.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. @@ -231,7 +231,7 @@ Logs user into the system ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var username = username_example; // String | The user name for login @@ -274,7 +274,7 @@ Logs out current logged in user session ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); @@ -312,7 +312,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'package:openapi/api.dart'; +import "package:openapi/api.dart"; var api_instance = UserApi(); var username = username_example; // String | name that need to be deleted 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 d31f9cc668ab..46e0011c8bff 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 @@ -94,7 +94,7 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; try { - switch(method.toUpperCase()) { + 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); @@ -103,13 +103,13 @@ class ApiClient { 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); + 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); + 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); + 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.withInner(400, "Exception occurred: $method $path", e, trace); } throw ApiException(400, "Invalid HTTP operation: $method $path"); 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 b8c6e5c7c22c..84da587ca2b7 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 @@ -39,7 +39,7 @@ class ApiResponse { message.hashCode; @override - String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; + String toString() => "ApiResponse[code=$code, type=$type, message=$message]"; ApiResponse.fromJson(Map json) { if (json == null) { 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 c5f3ae8b9da6..cca3b550ae0a 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 @@ -33,7 +33,7 @@ class Category { name.hashCode; @override - String toString() => 'Category[id=$id, name=$name]'; + String toString() => "Category[id=$id, name=$name]"; Category.fromJson(Map json) { if (json == null) { 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 2950c4456bcc..71d0b8576ca9 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 @@ -57,7 +57,7 @@ class Order { complete.hashCode; @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + String toString() => "Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]"; Order.fromJson(Map json) { if (json == null) { @@ -130,8 +130,7 @@ class OrderStatusEnum { final String value; @override - bool operator ==(Object other) => - identical(this, other) || + bool operator ==(Object other) => identical(this, other) || other is OrderStatusEnum && other.value == value || other is String && other == value; @@ -188,7 +187,7 @@ class OrderStatusEnumTypeTransformer { case "approved": return OrderStatusEnum.approved_; case "delivered": return OrderStatusEnum.delivered_; default: - if (false == allowNull) { + if (allowNull == false) { throw ArgumentError("Unknown enum value to decode: $data"); } } 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 06a16c04ff0b..2ddd2a848e8f 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 @@ -57,7 +57,7 @@ class Pet { status.hashCode; @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + String toString() => "Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]"; Pet.fromJson(Map json) { if (json == null) { @@ -130,8 +130,7 @@ class PetStatusEnum { final String value; @override - bool operator ==(Object other) => - identical(this, other) || + bool operator ==(Object other) => identical(this, other) || other is PetStatusEnum && other.value == value || other is String && other == value; @@ -188,7 +187,7 @@ class PetStatusEnumTypeTransformer { case "pending": return PetStatusEnum.pending_; case "sold": return PetStatusEnum.sold_; default: - if (false == allowNull) { + if (allowNull == false) { throw ArgumentError("Unknown enum value to decode: $data"); } } 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 4336ea79cdc3..8faa307d40f0 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 @@ -33,7 +33,7 @@ class Tag { name.hashCode; @override - String toString() => 'Tag[id=$id, name=$name]'; + String toString() => "Tag[id=$id, name=$name]"; Tag.fromJson(Map json) { if (json == null) { 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 17553d3b666a..7047cb1535f2 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 @@ -69,7 +69,7 @@ class User { userStatus.hashCode; @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String toString() => "User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]"; User.fromJson(Map json) { if (json == null) { From 7161f31ff42cd7ca5181543050eb3b8271c3c9b2 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 01:14:50 +0200 Subject: [PATCH 05/19] Wrap few more places with triple curly parentheses. --- .../src/main/resources/dart2/README.mustache | 36 +++++++++---------- .../src/main/resources/dart2/api_doc.mustache | 12 +++---- .../main/resources/dart2/api_test.mustache | 2 +- .../main/resources/dart2/object_doc.mustache | 2 +- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index 593b713ab375..66c70dbabc87 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}}(); +var api_instance = {{{classname}}}(); {{#allParams}} -var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +var {{{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}}var 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 @@ -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_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache index 91f670d7bd8e..322f74cde6d8 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -6,17 +6,17 @@ 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}} @@ -57,11 +57,11 @@ import "package:{{{pubName}}}/api.dart"; var api_instance = {{{classname}}}(); {{#allParams}} -var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +var {{{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}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#returnType}} print(result); {{/returnType}} @@ -74,7 +74,7 @@ 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 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 676b4ce9ae14..dc6c3d35458b 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache @@ -18,7 +18,7 @@ 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 + //{{#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/object_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache index fcc2f4c8f268..12290cdf7b7f 100644 --- a/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache @@ -1,4 +1,4 @@ -{{#models}}{{#model}}# {{{pubName}}}.model.{{classname}} +{{#models}}{{#model}}# {{{pubName}}}.model.{{{classname}}} ## Load the model package ```dart From c8c2b62a279a7fca24c0295524cac780e27c7bb9 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 01:16:04 +0200 Subject: [PATCH 06/19] Generated Petstore files. --- .../petstore/dart2/petstore_client_lib/doc/PetApi.md | 4 ++-- .../petstore/dart2/petstore_client_lib/doc/UserApi.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) 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 69a4c0b4d823..e19f7fbaec31 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md @@ -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 @@ -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 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 7b102ca0d91d..6188244f0a40 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md @@ -71,7 +71,7 @@ Creates list of users with given input array import "package:openapi/api.dart"; var api_instance = UserApi(); -var body = [List<User>()]; // List | List of user object +var body = [List()]; // List | List of user object try { api_instance.createUsersWithArrayInput(body); @@ -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 @@ -111,7 +111,7 @@ Creates list of users with given input array import "package:openapi/api.dart"; var api_instance = UserApi(); -var body = [List<User>()]; // List | List of user object +var body = [List()]; // List | List of user object try { api_instance.createUsersWithListInput(body); @@ -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 From 1cde1a8a296275d7f71da3120bfefc01927c0330 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 11:35:30 +0200 Subject: [PATCH 07/19] Revert to using single quotes, fix Java generator too. --- .../codegen/languages/DartClientCodegen.java | 4 +- .../languages/DartDioClientCodegen.java | 2 +- .../languages/DartJaguarClientCodegen.java | 2 +- .../src/main/resources/dart2/README.mustache | 20 ++--- .../src/main/resources/dart2/api.mustache | 56 +++++++------ .../main/resources/dart2/api_client.mustache | 80 ++++++++++--------- .../src/main/resources/dart2/api_doc.mustache | 20 ++--- .../resources/dart2/api_exception.mustache | 11 ++- .../main/resources/dart2/api_helper.mustache | 18 ++--- .../main/resources/dart2/api_test.mustache | 8 +- .../src/main/resources/dart2/apilib.mustache | 40 +++++----- .../dart2/auth/api_key_auth.mustache | 14 ++-- .../main/resources/dart2/auth/header.mustache | 1 - .../dart2/auth/http_basic_auth.mustache | 4 +- .../dart2/auth/http_bearer_auth.mustache | 8 +- .../main/resources/dart2/auth/oauth.mustache | 2 +- .../src/main/resources/dart2/class.mustache | 56 ++++++------- .../src/main/resources/dart2/enum.mustache | 2 +- .../main/resources/dart2/enum_inline.mustache | 2 +- .../src/main/resources/dart2/header.mustache | 1 - .../main/resources/dart2/model_test.mustache | 8 +- .../main/resources/dart2/object_doc.mustache | 2 +- 22 files changed, 179 insertions(+), 182 deletions(-) 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 72bd5c53154e..63b06c011172 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 @@ -410,7 +410,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 { @@ -533,7 +533,7 @@ public String toEnumValue(String value, String datatype) { "int".equalsIgnoreCase(datatype)) { return value; } else { - return "\"" + escapeText(value) + "\""; + return "'" + escapeText(value) + "'"; } } 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 8126ecf07be3..8db5297005d8 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 @@ -139,7 +139,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 { 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 b29946c56c51..53f049f4b9f7 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 @@ -141,7 +141,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 { diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index 66c70dbabc87..e60be4c4f8bc 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -48,34 +48,34 @@ 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}} {{#isBasic}} {{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").username = "YOUR_USERNAME" -//defaultApiClient.getAuthentication("{{{name}}}").password = "YOUR_PASSWORD"; +//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' +//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; {{/isBasicBasic}} {{#isBasicBearer}} // TODO Configure HTTP Bearer authorization: {{{name}}} // Case 1. Use String Token -//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken("YOUR_ACCESS_TOKEN"); +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); // Case 2. Use Function which generate token. // String yourTokenGeneratorFunction() { ... } -//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken(yourTokenGeneratorFunction); +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").apiKey = "YOUR_API_KEY"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication("{{{name}}}").apiKeyPrefix = "Bearer"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} @@ -91,7 +91,7 @@ try { 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}} ``` @@ -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 diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index fee3acc0d206..9bd1abf0ee60 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -12,56 +12,54 @@ class {{{classname}}} { /// /// {{{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 + // Verify required params are set. {{#allParams}} {{#required}} if ({{{paramName}}} == null) { - throw ApiException(400, "Missing required param: {{{paramName}}}"); + 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}} + {{^required}} if ({{{paramName}}} != null) { - {{/required}} - queryParams.addAll(_convertParametersForCollectionFormat("{{{collectionFormat}}}", "{{{baseName}}}", {{{paramName}}})); - {{^required}} + {{/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}}]; - - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = [{{#authMethods}}"{{{name}}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = [{{#authMethods}}'{{{name}}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); {{#formParams}} {{^isFile}} if ({{{paramName}}} != null) { hasFields = true; - mp.fields["{{{baseName}}}"] = parameterToString({{{paramName}}}); + mp.fields['{{{baseName}}}'] = parameterToString({{{paramName}}}); } {{/isFile}} {{#isFile}} if ({{{paramName}}} != null) { hasFields = true; - mp.fields["{{{baseName}}}"] = {{{paramName}}}.field; + mp.fields['{{{baseName}}}'] = {{{paramName}}}.field; mp.files.add({{{paramName}}}); } {{/isFile}} @@ -73,7 +71,7 @@ class {{{classname}}} { {{#formParams}} {{^isFile}} if ({{{paramName}}} != null) { - formParams["{{{baseName}}}"] = parameterToString({{{paramName}}}); + formParams['{{{baseName}}}'] = parameterToString({{{paramName}}}); } {{/isFile}} {{/formParams}} @@ -81,7 +79,7 @@ class {{{classname}}} { return await apiClient.invokeAPI( path, - "{{{httpMethod}}}", + '{{{httpMethod}}}', queryParams, postBody, headerParams, @@ -106,7 +104,7 @@ class {{{classname}}} { if (response.body != null) { {{#isListContainer}} {{#returnType}} - return (apiClient.deserialize(_decodeBodyBytes(response), "{{{returnType}}}") as List) + return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List) .map((item) => item as {{{returnBaseType}}}) .toList(growable: false); {{/returnType}} @@ -114,12 +112,12 @@ class {{{classname}}} { {{^isListContainer}} {{#isMapContainer}} {{#returnType}} - return {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), "{{{returnType}}}")); + return {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}')); {{/returnType}} {{/isMapContainer}} {{^isMapContainer}} {{#returnType}} - return apiClient.deserialize(_decodeBodyBytes(response), "{{{returnType}}}") as {{{returnType}}}; + return apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as {{{returnType}}}; {{/returnType}} {{/isMapContainer}} {{/isListContainer}} 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 01ecbbfe2bf7..49b30f963b85 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -8,23 +8,23 @@ class QueryParam { } class ApiClient { - 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}} @@ -42,14 +42,14 @@ class ApiClient { dynamic deserialize(String json, String targetType, {bool growable}) { // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(" ", ""); + targetType = targetType.replaceAll(' ', ''); - return targetType == "String" + return targetType == 'String' ? json : _deserialize(jsonDecode(json), targetType, growable: true == growable); } - String serialize(Object obj) => obj == null ? "" : json.encode(obj); + String serialize(Object obj) => obj == null ? '' : json.encode(obj); T getAuthentication(String name) { final authentication = _authentications[name]; @@ -57,7 +57,7 @@ class ApiClient { } // We don’t use a Map for queryParams. - // If collectionFormat is "multi" a key might appear multiple times. + // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, String method, @@ -74,14 +74,14 @@ class ApiClient { final ps = queryParams .where((p) => p.value != null) - .map((p) => "${p.name}=${Uri.encodeQueryComponent(p.value)}"); + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); - final queryString = ps.isNotEmpty ? "?" + ps.join("&") : ""; + final queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; - final url = "$basePath$path$queryString"; + final url = '$basePath$path$queryString'; if (nullableContentType != null) { - headerParams["Content-Type"] = nullableContentType; + headerParams['Content-Type'] = nullableContentType; } if (body is MultipartRequest) { @@ -94,50 +94,52 @@ class ApiClient { return Response.fromStream(response); } - final msgBody = nullableContentType == "application/x-www-form-urlencoded" + 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); + 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); + 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); + 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); + 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.withInner(400, 'Exception occurred: $method $path', e, trace); } - throw ApiException(400, "Invalid HTTP operation: $method $path"); + 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"; + 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"); + case 'double': + return value is double ? value : double.parse('$value'); {{#models}} {{#model}} - case "{{{classname}}}": + case '{{{classname}}}': {{#isEnum}} return {{{classname}}}TypeTransformer().decode(value); {{/isEnum}} @@ -164,9 +166,9 @@ class ApiClient { break; } } on Exception catch (e, stack) { - throw ApiException.withInner(500, "Exception during deserialization.", e, stack); + throw ApiException.withInner(500, 'Exception during deserialization.', e, stack); } - throw ApiException(500, "Could not find a suitable class for deserialization"); + throw ApiException(500, 'Could not find a suitable class for deserialization'); } /// Update query and header parameters based on authentication settings. @@ -179,7 +181,7 @@ class ApiClient { authNames.forEach((authName) { final auth = _authentications[authName]; if (auth == null) { - throw ArgumentError("Authentication undefined: $authName"); + throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); }); 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 322f74cde6d8..864845c6d198 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -3,7 +3,7 @@ ## Load the API package ```dart -import "package:{{{pubName}}}/api.dart"; +import 'package:{{{pubName}}}/api.dart'; ``` All URIs are relative to *{{{basePath}}}* @@ -24,33 +24,33 @@ Method | HTTP request | Description ### Example ```dart -import "package:{{{pubName}}}/api.dart"; +import 'package:{{{pubName}}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} {{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").username = "YOUR_USERNAME" -//defaultApiClient.getAuthentication("{{{name}}}").password = "YOUR_PASSWORD"; +//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' +//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; {{/isBasicBasic}} {{#isBasicBearer}} // TODO Configure HTTP Bearer authorization: {{{name}}} // Case 1. Use String Token -//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken("YOUR_ACCESS_TOKEN"); +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); // Case 2. Use Function which generate token. // String yourTokenGeneratorFunction() { ... } -//defaultApiClient.getAuthentication("{{{name}}}").setAccessToken(yourTokenGeneratorFunction); +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").apiKey = "YOUR_API_KEY"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication("{{{name}}}").apiKeyPrefix = "Bearer"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//defaultApiClient.getAuthentication("{{{name}}}").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} @@ -66,7 +66,7 @@ try { print(result); {{/returnType}} } catch (e) { - print("Exception when calling {{{classname}}}->{{{operationId}}}: $e\n"); + print('Exception when calling {{{classname}}}->{{{operationId}}}: $e\n'); } ``` 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 45c92d7c07f2..40f4fda731ee 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -11,13 +11,12 @@ class ApiException implements Exception { StackTrace 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 c281637288ab..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,6 +1,6 @@ {{>header}} {{>part_of}} -// port from Java version +// Ported from the Java version. Iterable _convertParametersForCollectionFormat( String collectionFormat, String name, @@ -13,14 +13,14 @@ Iterable _convertParametersForCollectionFormat( if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" + ? 'csv' : collectionFormat; - if (collectionFormat == "multi") { + if (collectionFormat == 'multi') { return value.map((v) => QueryParam(name, parameterToString(v))); } - final delimiter = _delimiters[collectionFormat] ?? ","; + final delimiter = _delimiters[collectionFormat] ?? ','; params.add(QueryParam(name, value.map((v) => parameterToString(v)).join(delimiter))); } else { @@ -34,7 +34,7 @@ Iterable _convertParametersForCollectionFormat( /// Format the given parameter object into a [String]. String parameterToString(dynamic value) { if (value == null) { - return ""; + return ''; } if (value is DateTime) { return value.toUtc().toIso8601String(); @@ -51,11 +51,11 @@ String parameterToString(dynamic value) { return value.toString(); } -/// 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. +/// 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) { - final contentType = response.headers["content-type"]; - return contentType != null && contentType.contains("application/json") + 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 dc6c3d35458b..e7d5828a5916 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache @@ -1,6 +1,6 @@ {{>header}} -import "package:{{{pubName}}}/api.dart"; -import "package:test/test.dart"; +import 'package:{{{pubName}}}/api.dart'; +import 'package:test/test.dart'; {{#operations}} @@ -8,7 +8,7 @@ import "package:test/test.dart"; void main() { var instance = {{{classname}}}(); - group("tests for {{{classname}}}", () { + group('tests for {{{classname}}}', () { {{#operation}} {{#summary}} // {{{.}}} @@ -19,7 +19,7 @@ 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 { + 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 ce6cdbbdfc6e..26fdc2237859 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -1,30 +1,30 @@ {{>header}} {{#pubLibrary}}library {{{pubLibrary}}};{{/pubLibrary}}{{^pubLibrary}}library {{{pubName}}}.api;{{/pubLibrary}} -import "dart:async"; -import "dart:convert"; -import "dart:io"; +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; -import "package:http/http.dart"; -import "package:intl/intl.dart"; -import "package:meta/meta.dart"; +import 'package:http/http.dart'; +import 'package:intl/intl.dart'; +import 'package:meta/meta.dart'; -part "api_client.dart"; -part "api_helper.dart"; -part "api_exception.dart"; -part "auth/authentication.dart"; -part "auth/api_key_auth.dart"; -part "auth/oauth.dart"; -part "auth/http_basic_auth.dart"; -part "auth/http_bearer_auth.dart"; +part 'api_client.dart'; +part 'api_helper.dart'; +part 'api_exception.dart'; +part 'auth/authentication.dart'; +part 'auth/api_key_auth.dart'; +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": "|"}; -final _dateFormatter = DateFormat("yyyy-MM-dd"); -final _regList = RegExp(r"^List<(.*)>$"); -final _regMap = RegExp(r"^Map$"); +const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; +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 fa3268fdcf3d..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 @@ -11,16 +11,16 @@ class ApiKeyAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final value = apiKeyPrefix == null ? apiKey : "$apiKeyPrefix $apiKey"; + final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; - if (location == "query" && value != null) { + if (location == 'query' && value != null) { queryParams.add(QueryParam(paramName, value)); - } else if (location == "header" && value != null) { + } else if (location == 'header' && value != null) { headerParams[paramName] = value; - } else if (location == "cookie" && value != null) { - headerParams.update("Cookie", (String existingCookie) { - return "$existingCookie; $paramName=$value"; - }, ifAbsent: () => "$paramName=$value"); + } else if (location == 'cookie' && value != null) { + headerParams.update('Cookie', (String existingCookie) { + return '$existingCookie; $paramName=$value'; + }, ifAbsent: () => '$paramName=$value'); } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache index cc03395da8de..15c11556cedb 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache @@ -6,4 +6,3 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes 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 3292ba6ab34b..4017bba38643 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 @@ -6,7 +6,7 @@ class HttpBasicAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic ${base64.encode(utf8.encode(str))}"; + final str = (username == null ? '' : username) + ':' + (password == null ? '' : password); + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(str))}'; } } 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 dd99aa73041a..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 @@ -11,7 +11,7 @@ class HttpBearerAuth implements Authentication { 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()."); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } this._accessToken = accessToken; } @@ -19,11 +19,11 @@ class HttpBearerAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { if (_accessToken is String) { - headerParams["Authorization"] = "Bearer $_accessToken"; + headerParams['Authorization'] = 'Bearer $_accessToken'; } else if (_accessToken is HttpBearerAuthProvider) { - headerParams["Authorization"] = "Bearer ${_accessToken()}"; + headerParams['Authorization'] = 'Bearer ${_accessToken()}'; } else { - throw ArgumentError("Type of Bearer accessToken should be a String or a String Function()."); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } } } 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 3b004d3c1925..6cdd30dceb27 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache @@ -8,7 +8,7 @@ class OAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { if (accessToken != null) { - headerParams["Authorization"] = "Bearer $accessToken"; + headerParams['Authorization'] = 'Bearer $accessToken'; } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index 80d77d59b374..d4967d0f4e73 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -1,7 +1,7 @@ class {{{classname}}} { {{{classname}}}({ {{#vars}} - {{#isNullable}}{{#required}}@required {{/required}}this.{{{name}}},{{/isNullable}}{{^isNullable}}{{#defaultValue}}this.{{{name}}} = {{#isContainer}}const {{/isContainer}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{#required}}@required {{/required}}this.{{{name}}}{{/defaultValue}},{{/isNullable}} + {{#isNullable}}{{#required}}@required {{/required}}this.{{{name}}},{{/isNullable}}{{^isNullable}}{{#defaultValue}}this.{{{name}}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{#required}}@required {{/required}}this.{{{name}}}{{/defaultValue}},{{/isNullable}} {{/vars}} }); @@ -40,7 +40,7 @@ class {{{classname}}} { {{/vars}} @override - String toString() => "{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]"; + String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; {{{classname}}}.fromJson(Map json) { if (json == null) { @@ -48,25 +48,25 @@ class {{{classname}}} { } {{#vars}} {{#isDateTime}} - {{{name}}} = json["{{{baseName}}}"] == null ? + {{{name}}} = json['{{{baseName}}}'] == null ? null : - DateTime.parse(json["{{{baseName}}}"]); + DateTime.parse(json['{{{baseName}}}']); {{/isDateTime}} {{#isDate}} - {{{name}}} = json["{{{baseName}}}"] == null ? + {{{name}}} = json['{{{baseName}}}'] == null ? null : - DateTime.parse(json["{{{baseName}}}"]); + DateTime.parse(json['{{{baseName}}}']); {{/isDate}} {{^isDateTime}} {{^isDate}} {{#complexType}} {{#isListContainer}} {{#items.isListContainer}} - {{{name}}} = json["{{{baseName}}}"] == null + {{{name}}} = json['{{{baseName}}}'] == null ? null - : (json["{{{baseName}}}"] as List).map( + : (json['{{{baseName}}}'] as List).map( {{#items.complexType}} - {{items.complexType}}.listFromJson(json["{{{baseName}}}"]) + {{items.complexType}}.listFromJson(json['{{{baseName}}}']) {{/items.complexType}} {{^items.complexType}} (e) => e == null ? null : (e as List).cast<{{items.items.dataType}}>() @@ -74,61 +74,61 @@ class {{{classname}}} { ).toList(growable: false); {{/items.isListContainer}} {{^items.isListContainer}} - {{{name}}} = {{{complexType}}}.listFromJson(json["{{{baseName}}}"]); + {{{name}}} = {{{complexType}}}.listFromJson(json['{{{baseName}}}']); {{/items.isListContainer}} {{/isListContainer}} {{^isListContainer}} {{#isMapContainer}} {{#items.isListContainer}} - {{{name}}} = json["{{{baseName}}}"] == null + {{{name}}} = json['{{{baseName}}}'] == null ? null {{#items.complexType}} - : {{items.complexType}}.mapListFromJson(json["{{{baseName}}}"]); + : {{items.complexType}}.mapListFromJson(json['{{{baseName}}}']); {{/items.complexType}} {{^items.complexType}} - : (json["{{{baseName}}}"] as Map).cast(); + : (json['{{{baseName}}}'] as Map).cast(); {{/items.complexType}} {{/items.isListContainer}} {{^items.isListContainer}} - {{{name}}} = json["{{{baseName}}}"] == null + {{{name}}} = json['{{{baseName}}}'] == null ? null - : {{{complexType}}}.mapFromJson(json["{{{baseName}}}"]); + : {{{complexType}}}.mapFromJson(json['{{{baseName}}}']); {{/items.isListContainer}} {{/isMapContainer}} {{^isMapContainer}} - {{{name}}} = {{{complexType}}}.fromJson(json["{{{baseName}}}"]); + {{{name}}} = {{{complexType}}}.fromJson(json['{{{baseName}}}']); {{/isMapContainer}} {{/isListContainer}} {{/complexType}} {{^complexType}} {{#isListContainer}} {{#isEnum}} - {{{name}}} = {{{classname}}}{{{items.datatypeWithEnum}}}.listFromJson(json["{{{baseName}}}"]); + {{{name}}} = {{{classname}}}{{{items.datatypeWithEnum}}}.listFromJson(json['{{{baseName}}}']); {{/isEnum}} {{^isEnum}} - {{{name}}} = json["{{{baseName}}}"] == null + {{{name}}} = json['{{{baseName}}}'] == null ? null - : (json["{{{baseName}}}"] as List).cast<{{{items.datatype}}}>(); + : (json['{{{baseName}}}'] as List).cast<{{{items.datatype}}}>(); {{/isEnum}} {{/isListContainer}} {{^isListContainer}} {{#isMapContainer}} - {{{name}}} = json["{{{baseName}}}"] == null ? + {{{name}}} = json['{{{baseName}}}'] == null ? null : - (json["{{{baseName}}}"] as Map).cast(); + (json['{{{baseName}}}'] as Map).cast(); {{/isMapContainer}} {{^isMapContainer}} {{#isNumber}} - {{{name}}} = json["{{{baseName}}}"] == null ? + {{{name}}} = json['{{{baseName}}}'] == null ? null : - json["{{{baseName}}}"].toDouble(); + 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}} @@ -144,14 +144,14 @@ class {{{classname}}} { {{#vars}} if ({{{name}}} != null) { {{#isDateTime}} - json["{{{baseName}}}"] = {{{name}}}.toUtc().toIso8601String(); + json['{{{baseName}}}'] = {{{name}}}.toUtc().toIso8601String(); {{/isDateTime}} {{#isDate}} - json["{{{baseName}}}"] = _dateFormatter.format({{{name}}}.toUtc()); + json['{{{baseName}}}'] = _dateFormatter.format({{{name}}}.toUtc()); {{/isDate}} {{^isDateTime}} {{^isDate}} - json["{{{baseName}}}"] = {{{name}}}; + json['{{{baseName}}}'] = {{{name}}}; {{/isDate}} {{/isDateTime}} } diff --git a/modules/openapi-generator/src/main/resources/dart2/enum.mustache b/modules/openapi-generator/src/main/resources/dart2/enum.mustache index 09a0008ed077..683e0d8528cc 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum.mustache @@ -76,7 +76,7 @@ class {{{classname}}}TypeTransformer { {{/allowableValues}} default: if (allowNull == false) { - throw ArgumentError("Unknown enum value to decode: $data"); + throw ArgumentError('Unknown enum value to decode: $data'); } } return null; 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 9408b2fcf96d..44ab77cceb5c 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum_inline.mustache @@ -76,7 +76,7 @@ class {{{classname}}}{{{enumName}}}TypeTransformer { {{/allowableValues}} default: if (allowNull == false) { - throw ArgumentError("Unknown enum value to decode: $data"); + throw ArgumentError('Unknown enum value to decode: $data'); } } return null; diff --git a/modules/openapi-generator/src/main/resources/dart2/header.mustache b/modules/openapi-generator/src/main/resources/dart2/header.mustache index cc03395da8de..15c11556cedb 100644 --- a/modules/openapi-generator/src/main/resources/dart2/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/header.mustache @@ -6,4 +6,3 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes 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 a468b4838062..5e4aeba5df99 100644 --- a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache @@ -1,7 +1,7 @@ {{#models}} {{#model}} -import "package:{{{pubName}}}/api.dart"; -import "package:test/test.dart"; +import 'package:{{{pubName}}}/api.dart'; +import 'package:test/test.dart'; // tests for {{{classname}}} void main() { @@ -9,13 +9,13 @@ void main() { var 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 { + 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 12290cdf7b7f..94402b858e0d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/object_doc.mustache @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:{{{pubName}}}/api.dart"; +import 'package:{{{pubName}}}/api.dart'; ``` ## Properties From 8019aab87ab350820a0d74df331da26232f2a68a Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 11:39:12 +0200 Subject: [PATCH 08/19] Generated Petstore files. --- .../dart2/petstore_client_lib/README.md | 6 +- .../petstore_client_lib/doc/ApiResponse.md | 2 +- .../dart2/petstore_client_lib/doc/Category.md | 2 +- .../dart2/petstore_client_lib/doc/Order.md | 2 +- .../dart2/petstore_client_lib/doc/Pet.md | 2 +- .../dart2/petstore_client_lib/doc/PetApi.md | 52 ++-- .../dart2/petstore_client_lib/doc/StoreApi.md | 22 +- .../dart2/petstore_client_lib/doc/Tag.md | 2 +- .../dart2/petstore_client_lib/doc/User.md | 2 +- .../dart2/petstore_client_lib/doc/UserApi.md | 34 +-- .../dart2/petstore_client_lib/lib/api.dart | 65 +++-- .../petstore_client_lib/lib/api/pet_api.dart | 269 ++++++++---------- .../lib/api/store_api.dart | 123 ++++---- .../petstore_client_lib/lib/api/user_api.dart | 249 ++++++++-------- .../petstore_client_lib/lib/api_client.dart | 87 +++--- .../lib/api_exception.dart | 12 +- .../petstore_client_lib/lib/api_helper.dart | 19 +- .../lib/auth/api_key_auth.dart | 15 +- .../lib/auth/authentication.dart | 1 - .../lib/auth/http_basic_auth.dart | 5 +- .../lib/auth/http_bearer_auth.dart | 9 +- .../petstore_client_lib/lib/auth/oauth.dart | 3 +- .../lib/model/api_response.dart | 15 +- .../lib/model/category.dart | 11 +- .../petstore_client_lib/lib/model/order.dart | 31 +- .../petstore_client_lib/lib/model/pet.dart | 35 ++- .../petstore_client_lib/lib/model/tag.dart | 11 +- .../petstore_client_lib/lib/model/user.dart | 35 ++- 28 files changed, 532 insertions(+), 589 deletions(-) diff --git a/samples/client/petstore/dart2/petstore_client_lib/README.md b/samples/client/petstore/dart2/petstore_client_lib/README.md index 877b0e588576..a8264638f3bc 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/README.md +++ b/samples/client/petstore/dart2/petstore_client_lib/README.md @@ -37,10 +37,10 @@ TODO Please follow the [installation procedure](#installation--usage) and then run the following: ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//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 @@ -48,7 +48,7 @@ var 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/ApiResponse.md b/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md index f6b10db5d194..7ad5da0f89e4 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/ApiResponse.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md index ffb7df6a5391..98d0b14be7b1 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Category.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md index 358ee59fcb15..bde5ffe51a2c 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Order.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties 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 4277e35a2488..88512ee37035 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Pet.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties 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 e19f7fbaec31..134d2a42108a 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/PetApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -26,9 +26,9 @@ Add a new pet to the store ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//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 @@ -36,7 +36,7 @@ var 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'); } ``` @@ -68,9 +68,9 @@ Deletes a pet ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = PetApi(); var petId = 789; // int | Pet id to delete @@ -79,7 +79,7 @@ var 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'); } ``` @@ -114,9 +114,9 @@ Multiple status values can be provided with comma separated strings ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -125,7 +125,7 @@ try { var 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'); } ``` @@ -159,9 +159,9 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = PetApi(); var tags = []; // List | Tags to filter by @@ -170,7 +170,7 @@ try { var 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'); } ``` @@ -204,11 +204,11 @@ Returns a single pet ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//defaultApiClient.getAuthentication("api_key").apiKey = "YOUR_API_KEY"; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication("api_key").apiKeyPrefix = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = PetApi(); var petId = 789; // int | ID of pet to return @@ -217,7 +217,7 @@ try { var 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'); } ``` @@ -249,9 +249,9 @@ Update an existing pet ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//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 @@ -259,7 +259,7 @@ var 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'); } ``` @@ -291,9 +291,9 @@ Updates a pet in the store with form data ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -303,7 +303,7 @@ var 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'); } ``` @@ -337,9 +337,9 @@ uploads an image ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//defaultApiClient.getAuthentication("petstore_auth").accessToken = "YOUR_ACCESS_TOKEN"; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = PetApi(); var petId = 789; // int | ID of pet to update @@ -350,7 +350,7 @@ try { var 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 cce6c734a169..9c5933109790 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/StoreApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,7 +24,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = StoreApi(); var orderId = orderId_example; // String | ID of the order that needs to be deleted @@ -32,7 +32,7 @@ var orderId = orderId_example; // String | ID of the order that needs to be dele try { api_instance.deleteOrder(orderId); } catch (e) { - print("Exception when calling StoreApi->deleteOrder: $e\n"); + print('Exception when calling StoreApi->deleteOrder: $e\n'); } ``` @@ -66,11 +66,11 @@ Returns a map of status codes to quantities ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//defaultApiClient.getAuthentication("api_key").apiKey = "YOUR_API_KEY"; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//defaultApiClient.getAuthentication("api_key").apiKeyPrefix = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = StoreApi(); @@ -78,7 +78,7 @@ try { var result = api_instance.getInventory(); print(result); } catch (e) { - print("Exception when calling StoreApi->getInventory: $e\n"); + print('Exception when calling StoreApi->getInventory: $e\n'); } ``` @@ -109,7 +109,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = StoreApi(); var orderId = 789; // int | ID of pet that needs to be fetched @@ -118,7 +118,7 @@ try { var 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'); } ``` @@ -150,7 +150,7 @@ Place an order for a pet ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = StoreApi(); var body = Order(); // Order | order placed for purchasing the pet @@ -159,7 +159,7 @@ try { var 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/Tag.md b/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md index a939b901f173..c219f987c19c 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/Tag.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties diff --git a/samples/client/petstore/dart2/petstore_client_lib/doc/User.md b/samples/client/petstore/dart2/petstore_client_lib/doc/User.md index 0a3686642a8f..fa87e64d8595 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/User.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/User.md @@ -2,7 +2,7 @@ ## Load the model package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` ## Properties 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 6188244f0a40..9fe5d2d7ff82 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md +++ b/samples/client/petstore/dart2/petstore_client_lib/doc/UserApi.md @@ -2,7 +2,7 @@ ## Load the API package ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; ``` All URIs are relative to *http://petstore.swagger.io/v2* @@ -28,7 +28,7 @@ This can only be done by the logged in user. ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var body = User(); // User | Created user object @@ -36,7 +36,7 @@ var 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'); } ``` @@ -68,7 +68,7 @@ Creates list of users with given input array ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var body = [List()]; // List | List of user object @@ -76,7 +76,7 @@ var 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'); } ``` @@ -108,7 +108,7 @@ Creates list of users with given input array ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var body = [List()]; // List | List of user object @@ -116,7 +116,7 @@ var 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'); } ``` @@ -150,7 +150,7 @@ This can only be done by the logged in user. ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var username = username_example; // String | The name that needs to be deleted @@ -158,7 +158,7 @@ var 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'); } ``` @@ -190,7 +190,7 @@ Get user by user name ### Example ```dart -import "package:openapi/api.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. @@ -199,7 +199,7 @@ try { var 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'); } ``` @@ -231,7 +231,7 @@ Logs user into the system ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var username = username_example; // String | The user name for login @@ -241,7 +241,7 @@ try { var 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'); } ``` @@ -274,14 +274,14 @@ Logs out current logged in user session ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var 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'); } ``` @@ -312,7 +312,7 @@ This can only be done by the logged in user. ### Example ```dart -import "package:openapi/api.dart"; +import 'package:openapi/api.dart'; var api_instance = UserApi(); var username = username_example; // String | name that need to be deleted @@ -321,7 +321,7 @@ var 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 ecc2e38b4723..7d6e6d0887c6 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -6,41 +6,40 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes 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"; - -part "api_client.dart"; -part "api_helper.dart"; -part "api_exception.dart"; -part "auth/authentication.dart"; -part "auth/api_key_auth.dart"; -part "auth/oauth.dart"; -part "auth/http_basic_auth.dart"; -part "auth/http_bearer_auth.dart"; - -part "api/pet_api.dart"; -part "api/store_api.dart"; -part "api/user_api.dart"; - -part "model/api_response.dart"; -part "model/category.dart"; -part "model/order.dart"; -part "model/pet.dart"; -part "model/tag.dart"; -part "model/user.dart"; - -const _delimiters = {"csv": ",", "ssv": " ", "tsv": "\t", "pipes": "|"}; -final _dateFormatter = DateFormat("yyyy-MM-dd"); -final _regList = RegExp(r"^List<(.*)>$"); -final _regMap = RegExp(r"^Map$"); +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart'; +import 'package:intl/intl.dart'; +import 'package:meta/meta.dart'; + +part 'api_client.dart'; +part 'api_helper.dart'; +part 'api_exception.dart'; +part 'auth/authentication.dart'; +part 'auth/api_key_auth.dart'; +part 'auth/oauth.dart'; +part 'auth/http_basic_auth.dart'; +part 'auth/http_bearer_auth.dart'; + +part 'api/pet_api.dart'; +part 'api/store_api.dart'; +part 'api/user_api.dart'; + +part 'model/api_response.dart'; +part 'model/category.dart'; +part 'model/order.dart'; +part 'model/pet.dart'; +part 'model/tag.dart'; +part 'model/user.dart'; + +const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; +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 5712a709aa54..190e46a1e371 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -20,29 +19,27 @@ class PetApi { /// /// Future addPetWithHttpInfo(Pet body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -51,7 +48,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -80,30 +77,28 @@ class PetApi { /// /// Future deletePetWithHttpInfo(int petId, { String apiKey }) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (petId == null) { - throw ApiException(400, "Missing required param: petId"); + 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()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - headerParams["api_key"] = apiKey; + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -112,7 +107,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "DELETE", + 'DELETE', queryParams, postBody, headerParams, @@ -143,30 +138,28 @@ class PetApi { /// /// Multiple status values can be provided with comma separated strings Future findPetsByStatusWithHttpInfo(List status) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (status == null) { - throw ApiException(400, "Missing required param: status"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -175,7 +168,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -196,7 +189,7 @@ class PetApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return (apiClient.deserialize(_decodeBodyBytes(response), "List") as List) + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) .map((item) => item as Pet) .toList(growable: false); } @@ -207,30 +200,28 @@ class PetApi { /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. Future findPetsByTagsWithHttpInfo(List tags) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (tags == null) { - throw ApiException(400, "Missing required param: tags"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -239,7 +230,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -260,7 +251,7 @@ class PetApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return (apiClient.deserialize(_decodeBodyBytes(response), "List") as List) + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) .map((item) => item as Pet) .toList(growable: false); } @@ -271,29 +262,27 @@ class PetApi { /// /// Returns a single pet Future getPetByIdWithHttpInfo(int petId) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (petId == null) { - throw ApiException(400, "Missing required param: petId"); + 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()); + + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -302,7 +291,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -323,7 +312,7 @@ class PetApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "Pet") as Pet; + return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; } return null; } @@ -332,29 +321,27 @@ class PetApi { /// /// Future updatePetWithHttpInfo(Pet body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -363,7 +350,7 @@ class PetApi { return await apiClient.invokeAPI( path, - "PUT", + 'PUT', queryParams, postBody, headerParams, @@ -392,52 +379,50 @@ class PetApi { /// /// Future updatePetWithFormWithHttpInfo(int petId, { String name, String status }) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (petId == null) { - throw ApiException(400, "Missing required param: petId"); + 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()); + + Object postBody; - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - List contentTypes = ["application/x-www-form-urlencoded"]; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = ["petstore_auth"]; + final contentTypes = ['application/x-www-form-urlencoded']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = ['petstore_auth']; - if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + if (nullableContentType != null && nullableContentType.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); + mp.fields['name'] = parameterToString(name); } if (status != null) { hasFields = true; - mp.fields["status"] = parameterToString(status); + mp.fields['status'] = parameterToString(status); } if (hasFields) { postBody = mp; } } else { if (name != null) { - formParams["name"] = parameterToString(name); + formParams['name'] = parameterToString(name); } if (status != null) { - formParams["status"] = parameterToString(status); + formParams['status'] = parameterToString(status); } } return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -470,36 +455,34 @@ class PetApi { /// /// Future uploadFileWithHttpInfo(int petId, { String additionalMetadata, MultipartFile file }) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (petId == null) { - throw ApiException(400, "Missing required param: petId"); + 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.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); + mp.fields['additionalMetadata'] = parameterToString(additionalMetadata); } if (file != null) { hasFields = true; - mp.fields["file"] = file.field; + mp.fields['file'] = file.field; mp.files.add(file); } if (hasFields) { @@ -507,13 +490,13 @@ class PetApi { } } else { if (additionalMetadata != null) { - formParams["additionalMetadata"] = parameterToString(additionalMetadata); + formParams['additionalMetadata'] = parameterToString(additionalMetadata); } } return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -538,7 +521,7 @@ class PetApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "ApiResponse") as ApiResponse; + return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; } 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 2f6b1cd7e338..b0b8cbaa55ce 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -20,29 +19,27 @@ class StoreApi { /// /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors Future deleteOrderWithHttpInfo(String orderId) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (orderId == null) { - throw ApiException(400, "Missing required param: orderId"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -51,7 +48,7 @@ class StoreApi { return await apiClient.invokeAPI( path, - "DELETE", + 'DELETE', queryParams, postBody, headerParams, @@ -80,26 +77,24 @@ class StoreApi { /// /// Returns a map of status codes to quantities 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -108,7 +103,7 @@ class StoreApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -127,7 +122,7 @@ class StoreApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return Map.from(apiClient.deserialize(_decodeBodyBytes(response), "Map")); + return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); } return null; } @@ -136,29 +131,27 @@ class StoreApi { /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions Future getOrderByIdWithHttpInfo(int orderId) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (orderId == null) { - throw ApiException(400, "Missing required param: orderId"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -167,7 +160,7 @@ class StoreApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -188,7 +181,7 @@ class StoreApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "Order") as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } return null; } @@ -197,29 +190,27 @@ class StoreApi { /// /// Future placeOrderWithHttpInfo(Order body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -228,7 +219,7 @@ class StoreApi { return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -249,7 +240,7 @@ class StoreApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "Order") as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } 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 290357ddc8e0..ecd267f8bf22 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -20,29 +19,27 @@ class UserApi { /// /// This can only be done by the logged in user. Future createUserWithHttpInfo(User body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -51,7 +48,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -80,29 +77,27 @@ class UserApi { /// /// Future createUsersWithArrayInputWithHttpInfo(List body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -111,7 +106,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -140,29 +135,27 @@ class UserApi { /// /// Future createUsersWithListInputWithHttpInfo(List body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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'); + + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -171,7 +164,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "POST", + 'POST', queryParams, postBody, headerParams, @@ -200,29 +193,27 @@ class UserApi { /// /// This can only be done by the logged in user. Future deleteUserWithHttpInfo(String username) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (username == null) { - throw ApiException(400, "Missing required param: username"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -231,7 +222,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "DELETE", + 'DELETE', queryParams, postBody, headerParams, @@ -260,29 +251,27 @@ class UserApi { /// /// Future getUserByNameWithHttpInfo(String username) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (username == null) { - throw ApiException(400, "Missing required param: username"); + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -291,7 +280,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -312,7 +301,7 @@ class UserApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "User") as User; + return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; } return null; } @@ -321,34 +310,32 @@ class UserApi { /// /// Future loginUserWithHttpInfo(String username, String password) async { - Object postBody; - - // verify required params are set + // Verify required params are set. if (username == null) { - throw ApiException(400, "Missing required param: username"); + throw ApiException(400, 'Missing required param: username'); } if (password == null) { - throw ApiException(400, "Missing required param: password"); + 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'); - // query params - List queryParams = []; - Map headerParams = {}; - Map formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); - queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); + Object postBody; - List contentTypes = []; + final queryParams = []; + final headerParams = {}; + final formParams = {}; - String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; - List authNames = []; + queryParams.addAll(_convertParametersForCollectionFormat('', 'username', username)); + queryParams.addAll(_convertParametersForCollectionFormat('', 'password', password)); - if (nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { + final contentTypes = []; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + if (nullableContentType != null && nullableContentType.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -357,7 +344,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -380,7 +367,7 @@ class UserApi { throw ApiException(response.statusCode, _decodeBodyBytes(response)); } if (response.body != null) { - return apiClient.deserialize(_decodeBodyBytes(response), "String") as String; + return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; } return null; } @@ -389,26 +376,24 @@ class UserApi { /// /// 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -417,7 +402,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "GET", + 'GET', queryParams, postBody, headerParams, @@ -444,32 +429,30 @@ class UserApi { /// /// This can only be done by the logged in user. Future updateUserWithHttpInfo(String username, User body) async { - Object postBody = body; - - // verify required params are set + // Verify required params are set. if (username == null) { - throw ApiException(400, "Missing required param: username"); + throw ApiException(400, 'Missing required param: username'); } if (body == null) { - throw ApiException(400, "Missing required param: body"); + 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()); + + 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.startsWith('multipart/form-data')) { bool hasFields = false; - MultipartRequest mp = MultipartRequest(null, null); + final mp = MultipartRequest(null, null); if (hasFields) { postBody = mp; } @@ -478,7 +461,7 @@ class UserApi { return await apiClient.invokeAPI( path, - "PUT", + 'PUT', queryParams, postBody, headerParams, 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 46e0011c8bff..fa35d2dbed3e 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -18,10 +17,10 @@ class QueryParam { } class ApiClient { - ApiClient({this.basePath = "http://petstore.swagger.io/v2"}) { + 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(); + _authentications['api_key'] = ApiKeyAuth('header', 'api_key'); + _authentications['petstore_auth'] = OAuth(); } String basePath; @@ -36,14 +35,14 @@ class ApiClient { dynamic deserialize(String json, String targetType, {bool growable}) { // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(" ", ""); + targetType = targetType.replaceAll(' ', ''); - return targetType == "String" + return targetType == 'String' ? json : _deserialize(jsonDecode(json), targetType, growable: true == growable); } - String serialize(Object obj) => obj == null ? "" : json.encode(obj); + String serialize(Object obj) => obj == null ? '' : json.encode(obj); T getAuthentication(String name) { final authentication = _authentications[name]; @@ -51,7 +50,7 @@ class ApiClient { } // We don’t use a Map for queryParams. - // If collectionFormat is "multi" a key might appear multiple times. + // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, String method, @@ -68,14 +67,14 @@ class ApiClient { final ps = queryParams .where((p) => p.value != null) - .map((p) => "${p.name}=${Uri.encodeQueryComponent(p.value)}"); + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); - final queryString = ps.isNotEmpty ? "?" + ps.join("&") : ""; + final queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; - final url = "$basePath$path$queryString"; + final url = '$basePath$path$queryString'; if (nullableContentType != null) { - headerParams["Content-Type"] = nullableContentType; + headerParams['Content-Type'] = nullableContentType; } if (body is MultipartRequest) { @@ -88,58 +87,60 @@ class ApiClient { return Response.fromStream(response); } - final msgBody = nullableContentType == "application/x-www-form-urlencoded" + 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); + 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); + 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); + 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); + 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.withInner(400, 'Exception occurred: $method $path', e, trace); } - throw ApiException(400, "Invalid HTTP operation: $method $path"); + 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"; + 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"); - case "ApiResponse": + case 'double': + return value is double ? value : double.parse('$value'); + case 'ApiResponse': return ApiResponse.fromJson(value); - case "Category": + case 'Category': return Category.fromJson(value); - case "Order": + case 'Order': return Order.fromJson(value); - case "Pet": + case 'Pet': return Pet.fromJson(value); - case "Tag": + case 'Tag': return Tag.fromJson(value); - case "User": + case 'User': return User.fromJson(value); default: Match match; @@ -159,9 +160,9 @@ class ApiClient { break; } } on Exception catch (e, stack) { - throw ApiException.withInner(500, "Exception during deserialization.", e, stack); + throw ApiException.withInner(500, 'Exception during deserialization.', e, stack); } - throw ApiException(500, "Could not find a suitable class for deserialization"); + throw ApiException(500, 'Could not find a suitable class for deserialization'); } /// Update query and header parameters based on authentication settings. @@ -174,7 +175,7 @@ class ApiClient { authNames.forEach((authName) { final auth = _authentications[authName]; if (auth == null) { - throw ArgumentError("Authentication undefined: $authName"); + throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); }); 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 4b5cca36c93f..7567f9064322 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -21,13 +20,12 @@ class ApiException implements Exception { StackTrace 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 4cea344ec792..e3236e175813 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 @@ -6,11 +6,10 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; -// port from Java version +// Ported from the Java version. Iterable _convertParametersForCollectionFormat( String collectionFormat, String name, @@ -23,14 +22,14 @@ Iterable _convertParametersForCollectionFormat( if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" + ? 'csv' : collectionFormat; - if (collectionFormat == "multi") { + if (collectionFormat == 'multi') { return value.map((v) => QueryParam(name, parameterToString(v))); } - final delimiter = _delimiters[collectionFormat] ?? ","; + final delimiter = _delimiters[collectionFormat] ?? ','; params.add(QueryParam(name, value.map((v) => parameterToString(v)).join(delimiter))); } else { @@ -44,7 +43,7 @@ Iterable _convertParametersForCollectionFormat( /// Format the given parameter object into a [String]. String parameterToString(dynamic value) { if (value == null) { - return ""; + return ''; } if (value is DateTime) { return value.toUtc().toIso8601String(); @@ -52,11 +51,11 @@ String parameterToString(dynamic value) { return value.toString(); } -/// 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. +/// 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) { - final contentType = response.headers["content-type"]; - return contentType != null && contentType.contains("application/json") + 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 67b9fd51c8c6..5189648aa096 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -21,16 +20,16 @@ class ApiKeyAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final value = apiKeyPrefix == null ? apiKey : "$apiKeyPrefix $apiKey"; + final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; - if (location == "query" && value != null) { + if (location == 'query' && value != null) { queryParams.add(QueryParam(paramName, value)); - } else if (location == "header" && value != null) { + } else if (location == 'header' && value != null) { headerParams[paramName] = value; - } else if (location == "cookie" && value != null) { - headerParams.update("Cookie", (String existingCookie) { - return "$existingCookie; $paramName=$value"; - }, ifAbsent: () => "$paramName=$value"); + } else if (location == 'cookie' && value != null) { + headerParams.update('Cookie', (String existingCookie) { + 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 b4110d0d7e5a..98b0a1effe32 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; 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 592d40d289fc..b8390b31bfce 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -16,7 +15,7 @@ class HttpBasicAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic ${base64.encode(utf8.encode(str))}"; + final str = (username == null ? '' : username) + ':' + (password == null ? '' : password); + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(str))}'; } } 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 f91e57a8ca0d..aa991105181f 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -21,7 +20,7 @@ class HttpBearerAuth implements Authentication { 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()."); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } this._accessToken = accessToken; } @@ -29,11 +28,11 @@ class HttpBearerAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { if (_accessToken is String) { - headerParams["Authorization"] = "Bearer $_accessToken"; + headerParams['Authorization'] = 'Bearer $_accessToken'; } else if (_accessToken is HttpBearerAuthProvider) { - headerParams["Authorization"] = "Bearer ${_accessToken()}"; + headerParams['Authorization'] = 'Bearer ${_accessToken()}'; } else { - throw ArgumentError("Type of Bearer accessToken should be a String or a String Function()."); + throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); } } } 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 f8923130f7bc..2dbfa61af324 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -18,7 +17,7 @@ class OAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { if (accessToken != null) { - headerParams["Authorization"] = "Bearer $accessToken"; + headerParams['Authorization'] = 'Bearer $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 84da587ca2b7..7409a68e2665 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -39,27 +38,27 @@ class ApiResponse { message.hashCode; @override - String toString() => "ApiResponse[code=$code, type=$type, message=$message]"; + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; ApiResponse.fromJson(Map json) { if (json == null) { return; } - code = json["code"]; - type = json["type"]; - message = json["message"]; + code = json['code']; + type = json['type']; + message = json['message']; } Map toJson() { final json = {}; if (code != null) { - json["code"] = code; + json['code'] = code; } if (type != null) { - json["type"] = type; + json['type'] = type; } if (message != null) { - json["message"] = message; + json['message'] = message; } return json; } 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 cca3b550ae0a..a22cd552ced7 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -33,23 +32,23 @@ class Category { name.hashCode; @override - String toString() => "Category[id=$id, name=$name]"; + String toString() => 'Category[id=$id, name=$name]'; Category.fromJson(Map json) { if (json == null) { return; } - id = json["id"]; - name = json["name"]; + id = json['id']; + name = json['name']; } Map toJson() { final json = {}; if (id != null) { - json["id"] = id; + json['id'] = id; } if (name != null) { - json["name"] = name; + json['name'] = name; } return json; } 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 71d0b8576ca9..c617320aa964 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -57,41 +56,41 @@ class Order { complete.hashCode; @override - String toString() => "Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]"; + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Order.fromJson(Map json) { if (json == null) { return; } - id = json["id"]; - petId = json["petId"]; - quantity = json["quantity"]; - shipDate = json["shipDate"] == 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"]; + DateTime.parse(json['shipDate']); + status = OrderStatusEnum.fromJson(json['status']); + complete = json['complete']; } Map toJson() { final json = {}; if (id != null) { - json["id"] = id; + json['id'] = id; } if (petId != null) { - json["petId"] = petId; + json['petId'] = petId; } if (quantity != null) { - json["quantity"] = quantity; + json['quantity'] = quantity; } if (shipDate != null) { - json["shipDate"] = shipDate.toUtc().toIso8601String(); + json['shipDate'] = shipDate.toUtc().toIso8601String(); } if (status != null) { - json["status"] = status; + json['status'] = status; } if (complete != null) { - json["complete"] = complete; + json['complete'] = complete; } return json; } @@ -188,7 +187,7 @@ class OrderStatusEnumTypeTransformer { case "delivered": return OrderStatusEnum.delivered_; default: if (allowNull == false) { - throw ArgumentError("Unknown enum value to decode: $data"); + throw ArgumentError('Unknown enum value to decode: $data'); } } return null; 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 2ddd2a848e8f..1a9add1854b7 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -15,8 +14,8 @@ class Pet { this.id, this.category, @required this.name, - this.photoUrls = const const [], - this.tags = const const [], + this.photoUrls = const [], + this.tags = const [], this.status, }); @@ -57,41 +56,41 @@ class Pet { status.hashCode; @override - String toString() => "Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]"; + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Pet.fromJson(Map json) { if (json == null) { return; } - id = json["id"]; - category = Category.fromJson(json["category"]); - name = json["name"]; - photoUrls = json["photoUrls"] == 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"]); + : (json['photoUrls'] as List).cast(); + tags = Tag.listFromJson(json['tags']); + status = PetStatusEnum.fromJson(json['status']); } Map toJson() { final json = {}; if (id != null) { - json["id"] = id; + json['id'] = id; } if (category != null) { - json["category"] = category; + json['category'] = category; } if (name != null) { - json["name"] = name; + json['name'] = name; } if (photoUrls != null) { - json["photoUrls"] = photoUrls; + json['photoUrls'] = photoUrls; } if (tags != null) { - json["tags"] = tags; + json['tags'] = tags; } if (status != null) { - json["status"] = status; + json['status'] = status; } return json; } @@ -188,7 +187,7 @@ class PetStatusEnumTypeTransformer { case "sold": return PetStatusEnum.sold_; default: if (allowNull == false) { - throw ArgumentError("Unknown enum value to decode: $data"); + throw ArgumentError('Unknown enum value to decode: $data'); } } return null; 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 8faa307d40f0..27d0558c9000 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -33,23 +32,23 @@ class Tag { name.hashCode; @override - String toString() => "Tag[id=$id, name=$name]"; + String toString() => 'Tag[id=$id, name=$name]'; Tag.fromJson(Map json) { if (json == null) { return; } - id = json["id"]; - name = json["name"]; + id = json['id']; + name = json['name']; } Map toJson() { final json = {}; if (id != null) { - json["id"] = id; + json['id'] = id; } if (name != null) { - json["name"] = name; + json['name'] = name; } return json; } 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 7047cb1535f2..d909d21fd157 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 @@ -6,7 +6,6 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars -// ignore_for_file: prefer_single_quotes part of openapi.api; @@ -69,47 +68,47 @@ class User { userStatus.hashCode; @override - String toString() => "User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]"; + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; 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"]; + id = json['id']; + username = json['username']; + firstName = json['firstName']; + lastName = json['lastName']; + email = json['email']; + password = json['password']; + phone = json['phone']; + userStatus = json['userStatus']; } Map toJson() { final json = {}; if (id != null) { - json["id"] = id; + json['id'] = id; } if (username != null) { - json["username"] = username; + json['username'] = username; } if (firstName != null) { - json["firstName"] = firstName; + json['firstName'] = firstName; } if (lastName != null) { - json["lastName"] = lastName; + json['lastName'] = lastName; } if (email != null) { - json["email"] = email; + json['email'] = email; } if (password != null) { - json["password"] = password; + json['password'] = password; } if (phone != null) { - json["phone"] = phone; + json['phone'] = phone; } if (userStatus != null) { - json["userStatus"] = userStatus; + json['userStatus'] = userStatus; } return json; } From 96ba839eea20c7cbf5a0f7eefd744c65ec47aff9 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 11:43:27 +0200 Subject: [PATCH 09/19] Lower case the content type value. --- modules/openapi-generator/src/main/resources/dart2/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 9bd1abf0ee60..99bf93e74360 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -43,7 +43,7 @@ class {{{classname}}} { {{/headerParams}} final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; - final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0].toLowerCase() : null; final authNames = [{{#authMethods}}'{{{name}}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; if (nullableContentType != null && nullableContentType.startsWith('multipart/form-data')) { From e761b0b09a6011d564cfb41803553bccd313f4c7 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 11:44:38 +0200 Subject: [PATCH 10/19] Only lower-case content type when checking its value. --- .../src/main/resources/dart2/api.mustache | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 99bf93e74360..720e7eba3025 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -43,10 +43,13 @@ class {{{classname}}} { {{/headerParams}} final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; - final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0].toLowerCase() : null; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final 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; final mp = MultipartRequest(null, null); {{#formParams}} From 44e929dcf1da8f8dca91d0a87a32b30aa61ead28 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 12:28:32 +0200 Subject: [PATCH 11/19] Generated files from running "./bin/utils/ensure-up-to-date". --- docs/generators/dart-dio.md | 4 +- docs/generators/dart-jaguar.md | 4 +- docs/generators/dart.md | 4 +- .../petstore_client_lib/lib/api/pet_api.dart | 40 +++++++++++++++---- .../lib/api/store_api.dart | 20 ++++++++-- .../petstore_client_lib/lib/api/user_api.dart | 40 +++++++++++++++---- 6 files changed, 86 insertions(+), 26 deletions(-) diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index 076f92f6b8e6..653d6ef473de 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -3,11 +3,10 @@ title: Config Options for dart-dio sidebar_label: dart-dio --- -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|browserClient|Is the client browser based (for Dart 1.x only)| |null| |dateLibrary|Option. Date library to use|
**core**
Dart core library (DateTime)
**timemachine**
Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.
|core| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| @@ -23,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| +|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING diff --git a/docs/generators/dart-jaguar.md b/docs/generators/dart-jaguar.md index e3c30cc7a1f7..d4430311aed4 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -3,11 +3,10 @@ title: Config Options for dart-jaguar sidebar_label: dart-jaguar --- -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|browserClient|Is the client browser based (for Dart 1.x only)| |null| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| @@ -23,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| +|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING diff --git a/docs/generators/dart.md b/docs/generators/dart.md index 42cb8b3bf58d..ea44c79ed38c 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -3,11 +3,10 @@ title: Config Options for dart sidebar_label: dart --- -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|browserClient|Is the client browser based (for Dart 1.x only)| |null| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| @@ -21,6 +20,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| +|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING 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 190e46a1e371..a2c496b26e79 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 @@ -37,7 +37,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -96,7 +99,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -157,7 +163,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -219,7 +228,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -280,7 +292,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -339,7 +354,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -397,7 +415,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (name != null) { @@ -473,7 +494,10 @@ class PetApi { 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; final mp = MultipartRequest(null, null); if (additionalMetadata != 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 b0b8cbaa55ce..ef6490193661 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 @@ -37,7 +37,10 @@ class StoreApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -92,7 +95,10 @@ class StoreApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -149,7 +155,10 @@ class StoreApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -208,7 +217,10 @@ class StoreApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { 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 ecd267f8bf22..f7aad0cb5619 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 @@ -37,7 +37,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -95,7 +98,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -153,7 +159,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -211,7 +220,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -269,7 +281,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -333,7 +348,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -391,7 +409,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { @@ -450,7 +471,10 @@ class UserApi { 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; final mp = MultipartRequest(null, null); if (hasFields) { From 6a5e77b370101aa6b85c0b05ca83aa5af3378b0c Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 12:35:55 +0200 Subject: [PATCH 12/19] Remove outdated comments for Dart1. --- docs/generators/dart-dio.md | 1 - docs/generators/dart-jaguar.md | 1 - docs/generators/dart.md | 1 - 3 files changed, 3 deletions(-) diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index 653d6ef473de..fe302afa2bfd 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -22,7 +22,6 @@ sidebar_label: dart-dio |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| -|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING diff --git a/docs/generators/dart-jaguar.md b/docs/generators/dart-jaguar.md index d4430311aed4..55ea98911a38 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -22,7 +22,6 @@ sidebar_label: dart-jaguar |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| -|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING diff --git a/docs/generators/dart.md b/docs/generators/dart.md index ea44c79ed38c..5bf6e99352e6 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -20,7 +20,6 @@ sidebar_label: dart |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|Source folder for generated code| |null| -|supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |useEnumExtension|Allow the 'x-enum-values' extension for enums| |null| ## IMPORT MAPPING From 8578a2aebc05e0265f8f3eac33aeb113e904b3cd Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 12:38:39 +0200 Subject: [PATCH 13/19] Regenerate Petstore samples for Dart. --- .../dart2/petstore_client_lib/lib/model/order.dart | 12 ++++++------ .../dart2/petstore_client_lib/lib/model/pet.dart | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) 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 c617320aa964..d63c8f030b8b 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 @@ -141,9 +141,9 @@ class OrderStatusEnum { String toJson() => value; - static const placed_ = OrderStatusEnum._("placed"); - static const approved_ = OrderStatusEnum._("approved"); - static const delivered_ = OrderStatusEnum._("delivered"); + 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 = [ @@ -182,9 +182,9 @@ class OrderStatusEnumTypeTransformer { /// 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_; + 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'); 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 1a9add1854b7..9377ed5c95e2 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 @@ -141,9 +141,9 @@ class PetStatusEnum { String toJson() => value; - static const available_ = PetStatusEnum._("available"); - static const pending_ = PetStatusEnum._("pending"); - static const sold_ = PetStatusEnum._("sold"); + 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 = [ @@ -182,9 +182,9 @@ class PetStatusEnumTypeTransformer { /// 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_; + 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'); From a7bab6a7b17dd6715f8a24e64e0a39099f8137f6 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Sun, 4 Oct 2020 13:00:41 +0200 Subject: [PATCH 14/19] Added a new option "pubLibrary". --- docs/generators/dart-dio.md | 4 +++- docs/generators/dart-jaguar.md | 4 +++- docs/generators/dart.md | 4 +++- .../codegen/languages/DartClientCodegen.java | 14 ++++++++++++++ .../codegen/languages/DartDioClientCodegen.java | 7 +++++++ .../codegen/languages/DartJaguarClientCodegen.java | 7 +++++++ .../codegen/dart/DartClientOptionsTest.java | 1 + .../codegen/dartdio/DartDioClientOptionsTest.java | 1 + .../codegen/options/DartClientOptionsProvider.java | 2 ++ .../options/DartDioClientOptionsProvider.java | 2 ++ 10 files changed, 43 insertions(+), 3 deletions(-) diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index fe302afa2bfd..f10e875630a7 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -3,10 +3,11 @@ title: Config Options for dart-dio sidebar_label: dart-dio --- +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|browserClient|Is the client browser based (for Dart 1.x only)| |null| |dateLibrary|Option. Date library to use|
**core**
Dart core library (DateTime)
**timemachine**
Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.
|core| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| @@ -17,6 +18,7 @@ sidebar_label: dart-dio |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 55ea98911a38..017dff4c4f81 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -3,10 +3,11 @@ title: Config Options for dart-jaguar sidebar_label: dart-jaguar --- +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|browserClient|Is the client browser based (for Dart 1.x only)| |null| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| @@ -16,6 +17,7 @@ sidebar_label: dart-jaguar |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 5bf6e99352e6..fbd5d7dd1d5c 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -3,10 +3,11 @@ title: Config Options for dart sidebar_label: dart --- +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|browserClient|Is the client browser based (for Dart 1.x only)| |null| |disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| @@ -15,6 +16,7 @@ sidebar_label: dart |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 63b06c011172..4d4123c90a38 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"; @@ -68,6 +69,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String USE_ENUM_EXTENSION = "useEnumExtension"; protected boolean browserClient = true; + protected String pubLibrary = "openapi.api"; protected String pubName = "openapi"; protected String pubVersion = "1.0.0"; protected String pubDescription = "OpenAPI API client"; @@ -170,6 +172,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")); @@ -215,6 +218,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 { @@ -553,6 +563,10 @@ public void setBrowserClient(boolean browserClient) { this.browserClient = browserClient; } + 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 8db5297005d8..707c1ff44124 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 @@ -188,6 +188,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 53f049f4b9f7..1dcfc7142ef0 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 @@ -173,6 +173,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/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) From 89816202eb821f1ff5d584c7ea4aed01cb5cab6d Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Tue, 6 Oct 2020 13:03:12 +0200 Subject: [PATCH 15/19] Added support for (de)serializing a DateTime into an epoch value. --- .../src/main/resources/dart2/README.mustache | 6 +- .../main/resources/dart2/api_client.mustache | 12 +- .../src/main/resources/dart2/api_doc.mustache | 6 +- .../main/resources/dart2/api_test.mustache | 2 +- .../src/main/resources/dart2/apilib.mustache | 1 + .../src/main/resources/dart2/class.mustache | 139 +++++++++++------- .../main/resources/dart2/model_test.mustache | 2 +- .../dart2/petstore_client_lib/README.md | 4 +- .../dart2/petstore_client_lib/doc/PetApi.md | 50 +++---- .../dart2/petstore_client_lib/doc/StoreApi.md | 20 +-- .../dart2/petstore_client_lib/doc/UserApi.md | 38 ++--- .../dart2/petstore_client_lib/lib/api.dart | 1 + .../petstore_client_lib/lib/api_client.dart | 12 +- .../lib/model/api_response.dart | 9 +- .../lib/model/category.dart | 7 +- .../petstore_client_lib/lib/model/order.dart | 19 ++- .../petstore_client_lib/lib/model/pet.dart | 19 ++- .../petstore_client_lib/lib/model/tag.dart | 7 +- .../petstore_client_lib/lib/model/user.dart | 19 ++- 19 files changed, 198 insertions(+), 175 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index e60be4c4f8bc..161d22c66a76 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -80,13 +80,13 @@ 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}} 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 49b30f963b85..2affd16a03d4 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -30,8 +30,8 @@ class ApiClient { {{/hasAuthMethods}} } - String basePath; - var client = Client(); + final String basePath; + final client = Client(); final _defaultHeaderMap = {}; final _authentications = {}; @@ -85,12 +85,12 @@ class ApiClient { } if (body is MultipartRequest) { - var request = MultipartRequest(method, Uri.parse(url)); + 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); } @@ -151,13 +151,13 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - var newTargetType = match[1]; + 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) { - var newTargetType = match[1]; + final newTargetType = match[1]; return Map.fromIterables( value.keys, value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), diff --git a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache index 864845c6d198..32f034829cca 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -55,13 +55,13 @@ 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}} 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 e7d5828a5916..3d783bf62d86 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache @@ -6,7 +6,7 @@ import 'package:test/test.dart'; /// tests for {{{classname}}} void main() { - var instance = {{{classname}}}(); + final instance = {{{classname}}}(); group('tests for {{{classname}}}', () { {{#operation}} diff --git a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache index 26fdc2237859..7502f877acdd 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -23,6 +23,7 @@ part 'auth/http_bearer_auth.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$'); diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index d4967d0f4e73..86d3811c22de 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -43,92 +43,104 @@ class {{{classname}}} { String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; {{{classname}}}.fromJson(Map json) { - if (json == null) { - return; - } + 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}} - {{#items.isListContainer}} - {{{name}}} = json['{{{baseName}}}'] == null - ? null - : (json['{{{baseName}}}'] as List).map( + {{#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) => e == null ? null : (e as List).cast<{{items.items.dataType}}>() + (e) => e == null ? null : (e as List).cast<{{items.items.dataType}}>() {{/items.complexType}} - ).toList(growable: false); - {{/items.isListContainer}} - {{^items.isListContainer}} - {{{name}}} = {{{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}} - : {{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}} + {{#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}} - {{#isEnum}} - {{{name}}} = {{{classname}}}{{{items.datatypeWithEnum}}}.listFromJson(json['{{{baseName}}}']); - {{/isEnum}} - {{^isEnum}} - {{{name}}} = json['{{{baseName}}}'] == null - ? null - : (json['{{{baseName}}}'] as List).cast<{{{items.datatype}}}>(); - {{/isEnum}} + {{#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}} @@ -137,6 +149,7 @@ class {{{classname}}} { {{/isDate}} {{/isDateTime}} {{/vars}} + } } Map toJson() { @@ -144,10 +157,24 @@ class {{{classname}}} { {{#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}} 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 5e4aeba5df99..3537d6085d6b 100644 --- a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache @@ -6,7 +6,7 @@ import 'package:test/test.dart'; // tests for {{{classname}}} void main() { {{^isEnum}} - var instance = {{{classname}}}(); + final instance = {{{classname}}}(); {{/isEnum}} group('test {{{classname}}}', () { diff --git a/samples/client/petstore/dart2/petstore_client_lib/README.md b/samples/client/petstore/dart2/petstore_client_lib/README.md index a8264638f3bc..0ebc02a14a66 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/README.md +++ b/samples/client/petstore/dart2/petstore_client_lib/README.md @@ -42,8 +42,8 @@ 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); 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 134d2a42108a..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,8 +30,8 @@ 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); @@ -72,9 +72,9 @@ 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); @@ -118,11 +118,11 @@ 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'); @@ -163,11 +163,11 @@ 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'); @@ -210,11 +210,11 @@ 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'); @@ -253,8 +253,8 @@ 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); @@ -295,10 +295,10 @@ 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); @@ -341,13 +341,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 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'); 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 9c5933109790..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,8 +26,8 @@ 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); @@ -72,10 +72,10 @@ 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'); @@ -111,11 +111,11 @@ 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'); @@ -152,11 +152,11 @@ 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'); 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 9fe5d2d7ff82..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,8 +30,8 @@ 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); @@ -70,8 +70,8 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var body = [List()]; // List | List of user object +final api_instance = UserApi(); +final body = [List()]; // List | List of user object try { api_instance.createUsersWithArrayInput(body); @@ -110,8 +110,8 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = UserApi(); -var body = [List()]; // List | List of user object +final api_instance = UserApi(); +final body = [List()]; // List | List of user object try { api_instance.createUsersWithListInput(body); @@ -152,8 +152,8 @@ 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); @@ -192,11 +192,11 @@ 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'); @@ -233,12 +233,12 @@ 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'); @@ -276,7 +276,7 @@ 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(); @@ -314,9 +314,9 @@ 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); 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 7d6e6d0887c6..0c5ef06b0a67 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -38,6 +38,7 @@ 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$'); 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 fa35d2dbed3e..d6299b4adef8 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 @@ -23,8 +23,8 @@ class ApiClient { _authentications['petstore_auth'] = OAuth(); } - String basePath; - var client = Client(); + final String basePath; + final client = Client(); final _defaultHeaderMap = {}; final _authentications = {}; @@ -78,12 +78,12 @@ class ApiClient { } if (body is MultipartRequest) { - var request = MultipartRequest(method, Uri.parse(url)); + 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); } @@ -145,13 +145,13 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - var newTargetType = match[1]; + 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) { - var newTargetType = match[1]; + final newTargetType = match[1]; return Map.fromIterables( value.keys, value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), 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 7409a68e2665..fdf32077ffbd 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 @@ -41,12 +41,11 @@ class ApiResponse { String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; ApiResponse.fromJson(Map json) { - if (json == null) { - return; + if (json != null) { + code = json['code']; + type = json['type']; + message = json['message']; } - code = json['code']; - type = json['type']; - message = json['message']; } Map toJson() { 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 a22cd552ced7..fa800ae0a3ae 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 @@ -35,11 +35,10 @@ class Category { String toString() => 'Category[id=$id, name=$name]'; Category.fromJson(Map json) { - if (json == null) { - return; + if (json != null) { + id = json['id']; + name = json['name']; } - id = json['id']; - name = json['name']; } Map toJson() { 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 d63c8f030b8b..94bce0d36932 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 @@ -59,17 +59,16 @@ class Order { String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Order.fromJson(Map json) { - if (json == null) { - return; + 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']; } - 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']; } Map toJson() { 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 9377ed5c95e2..a0cd75bfae1b 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 @@ -59,17 +59,16 @@ class Pet { String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Pet.fromJson(Map json) { - if (json == null) { - return; + 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']); } - 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']); } Map toJson() { 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 27d0558c9000..ed632cee9e58 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 @@ -35,11 +35,10 @@ class Tag { String toString() => 'Tag[id=$id, name=$name]'; Tag.fromJson(Map json) { - if (json == null) { - return; + if (json != null) { + id = json['id']; + name = json['name']; } - id = json['id']; - name = json['name']; } Map toJson() { 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 d909d21fd157..8a5e98d4e216 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 @@ -71,17 +71,16 @@ class User { String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; User.fromJson(Map json) { - if (json == null) { - return; + 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']; } - id = json['id']; - username = json['username']; - firstName = json['firstName']; - lastName = json['lastName']; - email = json['email']; - password = json['password']; - phone = json['phone']; - userStatus = json['userStatus']; } Map toJson() { From bcec0baded8f9b9e8f1d3c0bb99baa7ed7478b8a Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Tue, 6 Oct 2020 16:08:40 +0200 Subject: [PATCH 16/19] Make client variable a getter/setter, adjust docs. --- .../src/main/resources/dart2/api.mustache | 22 +- .../main/resources/dart2/api_client.mustache | 32 +- .../src/main/resources/dart2/class.mustache | 37 +- .../petstore_client_lib/lib/api/pet_api.dart | 131 +++--- .../lib/api/store_api.dart | 48 ++- .../petstore_client_lib/lib/api/user_api.dart | 110 +++-- .../petstore_client_lib/lib/api_client.dart | 32 +- .../lib/model/api_response.dart | 89 +++- .../lib/model/category.dart | 52 ++- .../petstore_client_lib/lib/model/order.dart | 258 +++++++++++- .../petstore_client_lib/lib/model/pet.dart | 258 +++++++++++- .../petstore_client_lib/lib/model/tag.dart | 52 ++- .../petstore_client_lib/lib/model/user.dart | 394 +++++++++++++++++- 13 files changed, 1238 insertions(+), 277 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 720e7eba3025..9f2ff8cca348 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -8,9 +8,11 @@ class {{{classname}}} { final ApiClient apiClient; {{#operation}} - /// {{{summary}}} with HTTP info returned + /// {{{summary}}} with HTTP info returned. + {{#notes}} /// - /// {{{notes}}} + /// {{{notes}}}. + {{/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 { // Verify required params are set. {{#allParams}} @@ -92,13 +94,19 @@ class {{{classname}}} { ); } - /// {{{summary}}} - /// + /// {{{summary}}}. {{#allParams}} - ///{{{dataType}}} {{{paramName}}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: - /// {{#description}} {{{description}}}{{/description}} + /// + /// Parameters: + /// * {{{dataType}}} {{{paramName}}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: + {{#description}} + /// {{{description}}} + {{/description}} {{/allParams}} - /// {{{notes}}} + {{#notes}} + /// + /// {{{notes}}}. + {{/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 { 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) { 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 2affd16a03d4..340978123e73 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -31,7 +31,23 @@ class ApiClient { } final String basePath; - final client = Client(); + + 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.'); + } + _client = newClient; + } final _defaultHeaderMap = {}; final _authentications = {}; @@ -90,7 +106,7 @@ class ApiClient { request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - final response = await client.send(request); + final response = await _client.send(request); return Response.fromStream(response); } @@ -101,12 +117,12 @@ class ApiClient { 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); + 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); diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index 86d3811c22de..2ca7d8c13ac7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -1,4 +1,5 @@ class {{{classname}}} { + /// Returns a new [{{{classname}}}] instance. {{{classname}}}({ {{#vars}} {{#isNullable}}{{#required}}@required {{/required}}this.{{{name}}},{{/isNullable}}{{^isNullable}}{{#defaultValue}}this.{{{name}}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{#required}}@required {{/required}}this.{{{name}}}{{/defaultValue}},{{/isNullable}} @@ -26,22 +27,10 @@ class {{{classname}}} { {{/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}}]'; - + /// Returns a new [{{{classname}}}] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [{{{classname}}}]'s properties. {{{classname}}}.fromJson(Map json) { if (json != null) { {{#vars}} @@ -186,6 +175,22 @@ class {{{classname}}} { return json; } + @override + String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; + + {{/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}} + static List<{{{classname}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : <{{{classname}}}>[] 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 a2c496b26e79..3e25f922ba8d 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 @@ -15,9 +15,7 @@ class PetApi { final ApiClient apiClient; - /// Add a new pet to the store with HTTP info returned - /// - /// + /// Add a new pet to the store with HTTP info returned. Future addPetWithHttpInfo(Pet body) async { // Verify required params are set. if (body == null) { @@ -61,11 +59,11 @@ class PetApi { ); } - /// Add a new pet to the store + /// 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 { final response = await addPetWithHttpInfo(body); if (response.statusCode >= 400) { @@ -76,9 +74,7 @@ class PetApi { return; } - /// Deletes a pet with HTTP info returned - /// - /// + /// Deletes a pet with HTTP info returned. Future deletePetWithHttpInfo(int petId, { String apiKey }) async { // Verify required params are set. if (petId == null) { @@ -123,13 +119,14 @@ class PetApi { ); } - /// Deletes a pet + /// Deletes a pet. /// - ///int petId (required): - /// Pet id to delete - ///String apiKey : - /// - /// + /// Parameters: + /// * int petId (required): + /// Pet id to delete + /// + /// Parameters: + /// * String apiKey : Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= 400) { @@ -140,9 +137,9 @@ class PetApi { return; } - /// Finds Pets by status with HTTP info returned + /// Finds Pets by status with HTTP info returned. /// - /// Multiple status values can be provided with comma separated strings + /// Multiple status values can be provided with comma separated strings. Future findPetsByStatusWithHttpInfo(List status) async { // Verify required params are set. if (status == null) { @@ -187,11 +184,13 @@ class PetApi { ); } - /// Finds Pets by status + /// Finds Pets by status. + /// + /// Parameters: + /// * List status (required): + /// Status values that need to be considered for filter /// - ///List status (required): - /// Status values that need to be considered for filter - /// Multiple status values can be provided with comma separated strings + /// Multiple status values can be provided with comma separated strings. Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= 400) { @@ -205,9 +204,9 @@ class PetApi { return null; } - /// Finds Pets by tags with HTTP info returned + /// Finds Pets by tags with HTTP info returned. /// - /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.. Future findPetsByTagsWithHttpInfo(List tags) async { // Verify required params are set. if (tags == null) { @@ -252,11 +251,13 @@ class PetApi { ); } - /// Finds Pets by tags + /// Finds Pets by tags. /// - ///List 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 + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.. Future> findPetsByTags(List tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= 400) { @@ -270,9 +271,9 @@ class PetApi { return null; } - /// Find pet by ID with HTTP info returned + /// Find pet by ID with HTTP info returned. /// - /// Returns a single pet + /// Returns a single pet. Future getPetByIdWithHttpInfo(int petId) async { // Verify required params are set. if (petId == null) { @@ -316,11 +317,13 @@ class PetApi { ); } - /// Find pet by ID + /// Find pet by ID. + /// + /// Parameters: + /// * int petId (required): + /// ID of pet to return /// - ///int petId (required): - /// ID of pet to return - /// Returns a single pet + /// Returns a single pet. Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= 400) { @@ -332,9 +335,7 @@ class PetApi { return null; } - /// Update an existing pet with HTTP info returned - /// - /// + /// Update an existing pet with HTTP info returned. Future updatePetWithHttpInfo(Pet body) async { // Verify required params are set. if (body == null) { @@ -378,11 +379,11 @@ class PetApi { ); } - /// Update an existing pet + /// 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 { final response = await updatePetWithHttpInfo(body); if (response.statusCode >= 400) { @@ -393,9 +394,7 @@ class PetApi { return; } - /// Updates a pet in the store with form data with HTTP info returned - /// - /// + /// Updates a pet in the store with form data with HTTP info returned. Future updatePetWithFormWithHttpInfo(int petId, { String name, String status }) async { // Verify required params are set. if (petId == null) { @@ -453,15 +452,19 @@ class PetApi { ); } - /// Updates a pet in the store with form data + /// Updates a pet in the store with form data. + /// + /// Parameters: + /// * int petId (required): + /// ID of pet that needs to be updated + /// + /// Parameters: + /// * String name : + /// Updated name of the pet /// - ///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: + /// * String status : + /// Updated status of the pet Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); if (response.statusCode >= 400) { @@ -472,9 +475,7 @@ class PetApi { return; } - /// uploads an image with HTTP info returned - /// - /// + /// uploads an image with HTTP info returned. Future uploadFileWithHttpInfo(int petId, { String additionalMetadata, MultipartFile file }) async { // Verify required params are set. if (petId == null) { @@ -530,15 +531,19 @@ class PetApi { ); } - /// uploads an image + /// uploads an image. + /// + /// Parameters: + /// * int petId (required): + /// ID of pet to update + /// + /// Parameters: + /// * String additionalMetadata : + /// Additional data to pass to server /// - ///int petId (required): - /// ID of pet to update - ///String additionalMetadata : - /// Additional data to pass to server - ///MultipartFile file : - /// file to upload - /// + /// Parameters: + /// * MultipartFile file : + /// file to upload Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); if (response.statusCode >= 400) { 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 ef6490193661..85bfc6526e7c 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 @@ -15,9 +15,9 @@ class StoreApi { final ApiClient apiClient; - /// Delete purchase order by ID with HTTP info returned + /// Delete purchase order by ID with HTTP info returned. /// - /// 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. Future deleteOrderWithHttpInfo(String orderId) async { // Verify required params are set. if (orderId == null) { @@ -61,11 +61,13 @@ class StoreApi { ); } - /// Delete purchase order by ID + /// 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 + /// Parameters: + /// * 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. Future deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= 400) { @@ -76,9 +78,9 @@ class StoreApi { return; } - /// Returns pet inventories by status with HTTP info returned + /// Returns pet inventories by status with HTTP info returned. /// - /// Returns a map of status codes to quantities + /// Returns a map of status codes to quantities. Future getInventoryWithHttpInfo() async { // Verify required params are set. @@ -119,9 +121,9 @@ class StoreApi { ); } - /// Returns pet inventories by status + /// Returns pet inventories by status. /// - /// Returns a map of status codes to quantities + /// Returns a map of status codes to quantities. Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= 400) { @@ -133,9 +135,9 @@ class StoreApi { return null; } - /// Find purchase order by ID with HTTP info returned + /// Find purchase order by ID with HTTP info returned. /// - /// 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. Future getOrderByIdWithHttpInfo(int orderId) async { // Verify required params are set. if (orderId == null) { @@ -179,11 +181,13 @@ class StoreApi { ); } - /// Find purchase order by ID + /// Find purchase order by ID. + /// + /// Parameters: + /// * int orderId (required): + /// ID of pet that needs to be fetched /// - ///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. Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= 400) { @@ -195,9 +199,7 @@ class StoreApi { return null; } - /// Place an order for a pet with HTTP info returned - /// - /// + /// Place an order for a pet with HTTP info returned. Future placeOrderWithHttpInfo(Order body) async { // Verify required params are set. if (body == null) { @@ -241,11 +243,11 @@ class StoreApi { ); } - /// Place an order for a pet + /// 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 { final response = await placeOrderWithHttpInfo(body); if (response.statusCode >= 400) { 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 f7aad0cb5619..4f464b488680 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 @@ -15,9 +15,9 @@ class UserApi { final ApiClient apiClient; - /// Create user with HTTP info returned + /// Create user with HTTP info returned. /// - /// This can only be done by the logged in user. + /// This can only be done by the logged in user.. Future createUserWithHttpInfo(User body) async { // Verify required params are set. if (body == null) { @@ -61,11 +61,13 @@ class UserApi { ); } - /// Create user + /// 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 + /// + /// This can only be done by the logged in user.. Future createUser(User body) async { final response = await createUserWithHttpInfo(body); if (response.statusCode >= 400) { @@ -76,9 +78,7 @@ class UserApi { return; } - /// Creates list of users with given input array with HTTP info returned - /// - /// + /// Creates list of users with given input array with HTTP info returned. Future createUsersWithArrayInputWithHttpInfo(List body) async { // Verify required params are set. if (body == null) { @@ -122,11 +122,11 @@ class UserApi { ); } - /// Creates list of users with given input array + /// Creates list of users with given input array. /// - ///List body (required): - /// List of user object - /// + /// Parameters: + /// * List body (required): + /// List of user object Future createUsersWithArrayInput(List body) async { final response = await createUsersWithArrayInputWithHttpInfo(body); if (response.statusCode >= 400) { @@ -137,9 +137,7 @@ class UserApi { return; } - /// Creates list of users with given input array with HTTP info returned - /// - /// + /// Creates list of users with given input array with HTTP info returned. Future createUsersWithListInputWithHttpInfo(List body) async { // Verify required params are set. if (body == null) { @@ -183,11 +181,11 @@ class UserApi { ); } - /// Creates list of users with given input array + /// Creates list of users with given input array. /// - ///List body (required): - /// List of user object - /// + /// Parameters: + /// * List body (required): + /// List of user object Future createUsersWithListInput(List body) async { final response = await createUsersWithListInputWithHttpInfo(body); if (response.statusCode >= 400) { @@ -198,9 +196,9 @@ class UserApi { return; } - /// Delete user with HTTP info returned + /// Delete user with HTTP info returned. /// - /// This can only be done by the logged in user. + /// This can only be done by the logged in user.. Future deleteUserWithHttpInfo(String username) async { // Verify required params are set. if (username == null) { @@ -244,11 +242,13 @@ class UserApi { ); } - /// Delete user + /// 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 + /// + /// This can only be done by the logged in user.. Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= 400) { @@ -259,9 +259,7 @@ class UserApi { return; } - /// Get user by user name with HTTP info returned - /// - /// + /// Get user by user name with HTTP info returned. Future getUserByNameWithHttpInfo(String username) async { // Verify required params are set. if (username == null) { @@ -305,11 +303,11 @@ class UserApi { ); } - /// Get user by user name + /// 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 { final response = await getUserByNameWithHttpInfo(username); if (response.statusCode >= 400) { @@ -321,9 +319,7 @@ class UserApi { return null; } - /// Logs user into the system with HTTP info returned - /// - /// + /// Logs user into the system with HTTP info returned. Future loginUserWithHttpInfo(String username, String password) async { // Verify required params are set. if (username == null) { @@ -372,13 +368,15 @@ class UserApi { ); } - /// Logs user into the system + /// 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 + /// + /// Parameters: + /// * String password (required): + /// The password for login in clear text Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); if (response.statusCode >= 400) { @@ -390,9 +388,7 @@ class UserApi { return null; } - /// Logs out current logged in user session with HTTP info returned - /// - /// + /// Logs out current logged in user session with HTTP info returned. Future logoutUserWithHttpInfo() async { // Verify required params are set. @@ -433,9 +429,7 @@ class UserApi { ); } - /// Logs out current logged in user session - /// - /// + /// Logs out current logged in user session. Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= 400) { @@ -446,9 +440,9 @@ class UserApi { return; } - /// Updated user with HTTP info returned + /// Updated user with HTTP info returned. /// - /// This can only be done by the logged in user. + /// This can only be done by the logged in user.. Future updateUserWithHttpInfo(String username, User body) async { // Verify required params are set. if (username == null) { @@ -495,13 +489,17 @@ class UserApi { ); } - /// Updated user + /// Updated user. + /// + /// Parameters: + /// * String username (required): + /// name that need to be deleted + /// + /// Parameters: + /// * User body (required): + /// Updated user object /// - ///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. + /// This can only be done by the logged in user.. Future updateUser(String username, User body) async { final response = await updateUserWithHttpInfo(username, body); if (response.statusCode >= 400) { 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 d6299b4adef8..7ac29d8b28ff 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 @@ -24,7 +24,23 @@ class ApiClient { } final String basePath; - final client = Client(); + + 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.'); + } + _client = newClient; + } final _defaultHeaderMap = {}; final _authentications = {}; @@ -83,7 +99,7 @@ class ApiClient { request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - final response = await client.send(request); + final response = await _client.send(request); return Response.fromStream(response); } @@ -94,12 +110,12 @@ class ApiClient { 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); + 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); 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 fdf32077ffbd..4907a2cf8b65 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 @@ -10,6 +10,7 @@ part of openapi.api; class ApiResponse { + /// Returns a new [ApiResponse] instance. ApiResponse({ this.code, this.type, @@ -19,27 +20,74 @@ class ApiResponse { int code; - - String type; + /// Returns a new [ApiResponse] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [ApiResponse]'s properties. + ApiResponse.fromJson(Map json) { + if (json != null) { + code = json['code']; + type = json['type']; + message = json['message']; + } + } - - String message; + Map toJson() { + final json = {}; + if (code != null) { + json['code'] = code; + } + if (type != null) { + json['type'] = type; + } + if (message != null) { + json['message'] = message; + } + return json; + } @override - bool operator ==(Object other) => identical(this, other) || other is ApiResponse && - other.code == code && - other.type == type && - other.message == message; + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; - @override - int get hashCode => - code.hashCode + - type.hashCode + - message.hashCode; + + String type; + + /// Returns a new [ApiResponse] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [ApiResponse]'s properties. + ApiResponse.fromJson(Map json) { + if (json != null) { + code = json['code']; + type = json['type']; + message = json['message']; + } + } + + Map toJson() { + final json = {}; + if (code != null) { + json['code'] = code; + } + if (type != null) { + json['type'] = type; + } + if (message != null) { + json['message'] = message; + } + return json; + } @override String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; + + String message; + + /// Returns a new [ApiResponse] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [ApiResponse]'s properties. ApiResponse.fromJson(Map json) { if (json != null) { code = json['code']; @@ -62,6 +110,21 @@ class ApiResponse { return json; } + @override + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; + + @override + bool operator ==(Object other) => identical(this, other) || other is ApiResponse && + other.code == code && + other.type == type && + other.message == message; + + @override + int get hashCode => + code.hashCode + + type.hashCode + + message.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 fa800ae0a3ae..e5459130f95c 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 @@ -10,6 +10,7 @@ part of openapi.api; class Category { + /// Returns a new [Category] instance. Category({ this.id, this.name, @@ -18,22 +19,38 @@ class Category { int id; - - String name; - - @override - bool operator ==(Object other) => identical(this, other) || other is Category && - other.id == id && - other.name == name; + /// Returns a new [Category] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Category]'s properties. + Category.fromJson(Map json) { + if (json != null) { + id = json['id']; + name = json['name']; + } + } - @override - int get hashCode => - id.hashCode + - name.hashCode; + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (name != null) { + json['name'] = name; + } + return json; + } @override String toString() => 'Category[id=$id, name=$name]'; + + String name; + + /// Returns a new [Category] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Category]'s properties. Category.fromJson(Map json) { if (json != null) { id = json['id']; @@ -52,6 +69,19 @@ class Category { return json; } + @override + String toString() => 'Category[id=$id, name=$name]'; + + @override + bool operator ==(Object other) => identical(this, other) || other is Category && + other.id == id && + other.name == name; + + @override + int get hashCode => + id.hashCode + + name.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 94bce0d36932..4ffc98f6e730 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 @@ -10,6 +10,7 @@ part of openapi.api; class Order { + /// Returns a new [Order] instance. Order({ this.id, this.petId, @@ -22,42 +23,240 @@ class Order { int id; + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (petId != null) { + json['petId'] = petId; + } + if (quantity != null) { + json['quantity'] = quantity; + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { + json['complete'] = complete; + } + return json; + } + + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + int petId; + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (petId != null) { + json['petId'] = petId; + } + if (quantity != null) { + json['quantity'] = quantity; + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { + json['complete'] = complete; + } + return json; + } + + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + int quantity; + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (petId != null) { + json['petId'] = petId; + } + if (quantity != null) { + json['quantity'] = quantity; + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { + json['complete'] = complete; + } + return json; + } + + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + DateTime shipDate; - /// Order Status - OrderStatusEnum status; + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. + 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']; + } + } - - bool complete; + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (petId != null) { + json['petId'] = petId; + } + if (quantity != null) { + json['quantity'] = quantity; + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { + json['complete'] = complete; + } + return json; + } @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; + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; - @override - int get hashCode => - id.hashCode + - petId.hashCode + - quantity.hashCode + - shipDate.hashCode + - status.hashCode + - complete.hashCode; + /// Order Status + OrderStatusEnum status; + + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (petId != null) { + json['petId'] = petId; + } + if (quantity != null) { + json['quantity'] = quantity; + } + if (shipDate != null) { + json['shipDate'] = shipDate.toUtc().toIso8601String(); + } + if (status != null) { + json['status'] = status; + } + if (complete != null) { + json['complete'] = complete; + } + return json; + } @override String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + + bool complete; + + /// Returns a new [Order] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Order]'s properties. Order.fromJson(Map json) { if (json != null) { id = json['id']; @@ -94,6 +293,27 @@ class Order { return json; } + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + + @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 + int get hashCode => + id.hashCode + + petId.hashCode + + quantity.hashCode + + shipDate.hashCode + + status.hashCode + + complete.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 a0cd75bfae1b..e1d0a0a8b1ec 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 @@ -10,6 +10,7 @@ part of openapi.api; class Pet { + /// Returns a new [Pet] instance. Pet({ this.id, this.category, @@ -22,42 +23,240 @@ class Pet { int id; + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. + 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']); + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (category != null) { + json['category'] = category; + } + if (name != null) { + json['name'] = name; + } + if (photoUrls != null) { + json['photoUrls'] = photoUrls; + } + if (tags != null) { + json['tags'] = tags; + } + if (status != null) { + json['status'] = status; + } + return json; + } + + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + Category category; + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. + 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']); + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (category != null) { + json['category'] = category; + } + if (name != null) { + json['name'] = name; + } + if (photoUrls != null) { + json['photoUrls'] = photoUrls; + } + if (tags != null) { + json['tags'] = tags; + } + if (status != null) { + json['status'] = status; + } + return json; + } + + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + String name; + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. + 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']); + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (category != null) { + json['category'] = category; + } + if (name != null) { + json['name'] = name; + } + if (photoUrls != null) { + json['photoUrls'] = photoUrls; + } + if (tags != null) { + json['tags'] = tags; + } + if (status != null) { + json['status'] = status; + } + return json; + } + + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + List photoUrls; - - List tags; + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. + 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']); + } + } - /// pet status in the store - PetStatusEnum status; + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (category != null) { + json['category'] = category; + } + if (name != null) { + json['name'] = name; + } + if (photoUrls != null) { + json['photoUrls'] = photoUrls; + } + if (tags != null) { + json['tags'] = tags; + } + if (status != null) { + json['status'] = status; + } + return json; + } @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; + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; - @override - int get hashCode => - id.hashCode + - category.hashCode + - name.hashCode + - photoUrls.hashCode + - tags.hashCode + - status.hashCode; + + List tags; + + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. + 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']); + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (category != null) { + json['category'] = category; + } + if (name != null) { + json['name'] = name; + } + if (photoUrls != null) { + json['photoUrls'] = photoUrls; + } + if (tags != null) { + json['tags'] = tags; + } + if (status != null) { + json['status'] = status; + } + return json; + } @override String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + /// pet status in the store + PetStatusEnum status; + + /// Returns a new [Pet] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Pet]'s properties. Pet.fromJson(Map json) { if (json != null) { id = json['id']; @@ -94,6 +293,27 @@ class Pet { return json; } + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$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 + int get hashCode => + id.hashCode + + category.hashCode + + name.hashCode + + photoUrls.hashCode + + tags.hashCode + + status.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 ed632cee9e58..67b359854abd 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 @@ -10,6 +10,7 @@ part of openapi.api; class Tag { + /// Returns a new [Tag] instance. Tag({ this.id, this.name, @@ -18,22 +19,38 @@ class Tag { int id; - - String name; - - @override - bool operator ==(Object other) => identical(this, other) || other is Tag && - other.id == id && - other.name == name; + /// Returns a new [Tag] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Tag]'s properties. + Tag.fromJson(Map json) { + if (json != null) { + id = json['id']; + name = json['name']; + } + } - @override - int get hashCode => - id.hashCode + - name.hashCode; + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (name != null) { + json['name'] = name; + } + return json; + } @override String toString() => 'Tag[id=$id, name=$name]'; + + String name; + + /// Returns a new [Tag] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [Tag]'s properties. Tag.fromJson(Map json) { if (json != null) { id = json['id']; @@ -52,6 +69,19 @@ class Tag { return json; } + @override + String toString() => 'Tag[id=$id, name=$name]'; + + @override + bool operator ==(Object other) => identical(this, other) || other is Tag && + other.id == id && + other.name == name; + + @override + int get hashCode => + id.hashCode + + name.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 8a5e98d4e216..784f8960f22f 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 @@ -10,6 +10,7 @@ part of openapi.api; class User { + /// Returns a new [User] instance. User({ this.id, this.username, @@ -24,52 +25,374 @@ class User { int id; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String username; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String firstName; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String lastName; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String email; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } + + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + String password; - - String phone; + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } - /// User Status - int userStatus; + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } @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; + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - @override - int get hashCode => - id.hashCode + - username.hashCode + - firstName.hashCode + - lastName.hashCode + - email.hashCode + - password.hashCode + - phone.hashCode + - userStatus.hashCode; + + String phone; + + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. + 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']; + } + } + + Map toJson() { + final json = {}; + if (id != null) { + json['id'] = id; + } + if (username != null) { + json['username'] = username; + } + if (firstName != null) { + json['firstName'] = firstName; + } + if (lastName != null) { + json['lastName'] = lastName; + } + if (email != null) { + json['email'] = email; + } + if (password != null) { + json['password'] = password; + } + if (phone != null) { + json['phone'] = phone; + } + if (userStatus != null) { + json['userStatus'] = userStatus; + } + return json; + } @override String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + /// User Status + int userStatus; + + /// Returns a new [User] instance. + /// + /// If [json] [Map] is non-null, its keys and values are mapped to + /// [User]'s properties. User.fromJson(Map json) { if (json != null) { id = json['id']; @@ -112,6 +435,31 @@ class User { return json; } + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$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 + int get hashCode => + id.hashCode + + username.hashCode + + firstName.hashCode + + lastName.hashCode + + email.hashCode + + password.hashCode + + phone.hashCode + + userStatus.hashCode; + static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] From 991fcf6c7a7b99b81ef99b8826c5495789a78470 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Tue, 6 Oct 2020 16:26:02 +0200 Subject: [PATCH 17/19] Fixed a small error in class template. --- .../src/main/resources/dart2/class.mustache | 80 ++-- .../lib/model/api_response.dart | 94 +---- .../lib/model/category.dart | 59 +-- .../petstore_client_lib/lib/model/order.dart | 263 +----------- .../petstore_client_lib/lib/model/pet.dart | 263 +----------- .../petstore_client_lib/lib/model/tag.dart | 59 +-- .../petstore_client_lib/lib/model/user.dart | 399 ++---------------- 7 files changed, 161 insertions(+), 1056 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/class.mustache b/modules/openapi-generator/src/main/resources/dart2/class.mustache index 2ca7d8c13ac7..84380954d8fa 100644 --- a/modules/openapi-generator/src/main/resources/dart2/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/class.mustache @@ -6,31 +6,8 @@ class {{{classname}}} { {{/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}} - - /// Returns a new [{{{classname}}}] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [{{{classname}}}]'s properties. + /// 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}} @@ -141,6 +118,43 @@ class {{{classname}}} { } } + {{#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() { final json = {}; {{#vars}} @@ -175,22 +189,6 @@ class {{{classname}}} { return json; } - @override - String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; - - {{/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}} - static List<{{{classname}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : <{{{classname}}}>[] 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 4907a2cf8b65..97dfbc13c6d8 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 @@ -17,13 +17,8 @@ class ApiResponse { this.message, }); - - int code; - - /// Returns a new [ApiResponse] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [ApiResponse]'s properties. + /// 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']; @@ -32,69 +27,29 @@ class ApiResponse { } } - Map toJson() { - final json = {}; - if (code != null) { - json['code'] = code; - } - if (type != null) { - json['type'] = type; - } - if (message != null) { - json['message'] = message; - } - return json; - } - - @override - String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; + + int code; String type; - /// Returns a new [ApiResponse] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [ApiResponse]'s properties. - ApiResponse.fromJson(Map json) { - if (json != null) { - code = json['code']; - type = json['type']; - message = json['message']; - } - } - - Map toJson() { - final json = {}; - if (code != null) { - json['code'] = code; - } - if (type != null) { - json['type'] = type; - } - if (message != null) { - json['message'] = message; - } - return json; - } + + String message; @override - String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; + bool operator ==(Object other) => identical(this, other) || other is ApiResponse && + other.code == code && + other.type == type && + other.message == message; - - String message; + @override + int get hashCode => + code.hashCode + + type.hashCode + + message.hashCode; - /// Returns a new [ApiResponse] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [ApiResponse]'s properties. - ApiResponse.fromJson(Map json) { - if (json != null) { - code = json['code']; - type = json['type']; - message = json['message']; - } - } + @override + String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; Map toJson() { final json = {}; @@ -110,21 +65,6 @@ class ApiResponse { return json; } - @override - String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; - - @override - bool operator ==(Object other) => identical(this, other) || other is ApiResponse && - other.code == code && - other.type == type && - other.message == message; - - @override - int get hashCode => - code.hashCode + - type.hashCode + - message.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 e5459130f95c..0d58f0627080 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 @@ -16,13 +16,8 @@ class Category { this.name, }); - - int id; - - /// Returns a new [Category] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Category]'s properties. + /// 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']; @@ -30,33 +25,24 @@ class Category { } } - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (name != null) { - json['name'] = name; - } - return json; - } - - @override - String toString() => 'Category[id=$id, name=$name]'; + + int id; String name; - /// Returns a new [Category] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Category]'s properties. - Category.fromJson(Map json) { - if (json != null) { - id = json['id']; - name = json['name']; - } - } + @override + bool operator ==(Object other) => identical(this, other) || other is Category && + other.id == id && + other.name == name; + + @override + int get hashCode => + id.hashCode + + name.hashCode; + + @override + String toString() => 'Category[id=$id, name=$name]'; Map toJson() { final json = {}; @@ -69,19 +55,6 @@ class Category { return json; } - @override - String toString() => 'Category[id=$id, name=$name]'; - - @override - bool operator ==(Object other) => identical(this, other) || other is Category && - other.id == id && - other.name == name; - - @override - int get hashCode => - id.hashCode + - name.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 4ffc98f6e730..25dda095b85b 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 @@ -20,13 +20,8 @@ class Order { this.complete = false, }); - - int id; - - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. + /// 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']; @@ -40,235 +35,44 @@ class Order { } } - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (petId != null) { - json['petId'] = petId; - } - if (quantity != null) { - json['quantity'] = quantity; - } - if (shipDate != null) { - json['shipDate'] = shipDate.toUtc().toIso8601String(); - } - if (status != null) { - json['status'] = status; - } - if (complete != null) { - json['complete'] = complete; - } - return json; - } - - @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + + int id; int petId; - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (petId != null) { - json['petId'] = petId; - } - if (quantity != null) { - json['quantity'] = quantity; - } - if (shipDate != null) { - json['shipDate'] = shipDate.toUtc().toIso8601String(); - } - if (status != null) { - json['status'] = status; - } - if (complete != null) { - json['complete'] = complete; - } - return json; - } - - @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; - int quantity; - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (petId != null) { - json['petId'] = petId; - } - if (quantity != null) { - json['quantity'] = quantity; - } - if (shipDate != null) { - json['shipDate'] = shipDate.toUtc().toIso8601String(); - } - if (status != null) { - json['status'] = status; - } - if (complete != null) { - json['complete'] = complete; - } - return json; - } - - @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; - DateTime shipDate; - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (petId != null) { - json['petId'] = petId; - } - if (quantity != null) { - json['quantity'] = quantity; - } - if (shipDate != null) { - json['shipDate'] = shipDate.toUtc().toIso8601String(); - } - if (status != null) { - json['status'] = status; - } - if (complete != null) { - json['complete'] = complete; - } - return json; - } - - @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; - /// Order Status OrderStatusEnum status; - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (petId != null) { - json['petId'] = petId; - } - if (quantity != null) { - json['quantity'] = quantity; - } - if (shipDate != null) { - json['shipDate'] = shipDate.toUtc().toIso8601String(); - } - if (status != null) { - json['status'] = status; - } - if (complete != null) { - json['complete'] = complete; - } - return json; - } + + bool complete; @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; + 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; - - bool complete; + @override + int get hashCode => + id.hashCode + + petId.hashCode + + quantity.hashCode + + shipDate.hashCode + + status.hashCode + + complete.hashCode; - /// Returns a new [Order] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Order]'s properties. - 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']; - } - } + @override + String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Map toJson() { final json = {}; @@ -293,27 +97,6 @@ class Order { return json; } - @override - String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; - - @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 - int get hashCode => - id.hashCode + - petId.hashCode + - quantity.hashCode + - shipDate.hashCode + - status.hashCode + - complete.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 e1d0a0a8b1ec..53704e252116 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 @@ -20,13 +20,8 @@ class Pet { this.status, }); - - int id; - - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. + /// 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']; @@ -40,235 +35,44 @@ class Pet { } } - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (category != null) { - json['category'] = category; - } - if (name != null) { - json['name'] = name; - } - if (photoUrls != null) { - json['photoUrls'] = photoUrls; - } - if (tags != null) { - json['tags'] = tags; - } - if (status != null) { - json['status'] = status; - } - return json; - } - - @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + + int id; Category category; - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. - 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']); - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (category != null) { - json['category'] = category; - } - if (name != null) { - json['name'] = name; - } - if (photoUrls != null) { - json['photoUrls'] = photoUrls; - } - if (tags != null) { - json['tags'] = tags; - } - if (status != null) { - json['status'] = status; - } - return json; - } - - @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; - String name; - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. - 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']); - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (category != null) { - json['category'] = category; - } - if (name != null) { - json['name'] = name; - } - if (photoUrls != null) { - json['photoUrls'] = photoUrls; - } - if (tags != null) { - json['tags'] = tags; - } - if (status != null) { - json['status'] = status; - } - return json; - } - - @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; - List photoUrls; - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. - 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']); - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (category != null) { - json['category'] = category; - } - if (name != null) { - json['name'] = name; - } - if (photoUrls != null) { - json['photoUrls'] = photoUrls; - } - if (tags != null) { - json['tags'] = tags; - } - if (status != null) { - json['status'] = status; - } - return json; - } - - @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; - List tags; - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. - 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']); - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (category != null) { - json['category'] = category; - } - if (name != null) { - json['name'] = name; - } - if (photoUrls != null) { - json['photoUrls'] = photoUrls; - } - if (tags != null) { - json['tags'] = tags; - } - if (status != null) { - json['status'] = status; - } - return json; - } + /// pet status in the store + PetStatusEnum status; @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; + 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; - /// pet status in the store - PetStatusEnum status; + @override + int get hashCode => + id.hashCode + + category.hashCode + + name.hashCode + + photoUrls.hashCode + + tags.hashCode + + status.hashCode; - /// Returns a new [Pet] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Pet]'s properties. - 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']); - } - } + @override + String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Map toJson() { final json = {}; @@ -293,27 +97,6 @@ class Pet { return json; } - @override - String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$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 - int get hashCode => - id.hashCode + - category.hashCode + - name.hashCode + - photoUrls.hashCode + - tags.hashCode + - status.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 67b359854abd..1b12e0194b5b 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 @@ -16,13 +16,8 @@ class Tag { this.name, }); - - int id; - - /// Returns a new [Tag] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Tag]'s properties. + /// 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']; @@ -30,33 +25,24 @@ class Tag { } } - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (name != null) { - json['name'] = name; - } - return json; - } - - @override - String toString() => 'Tag[id=$id, name=$name]'; + + int id; String name; - /// Returns a new [Tag] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [Tag]'s properties. - Tag.fromJson(Map json) { - if (json != null) { - id = json['id']; - name = json['name']; - } - } + @override + bool operator ==(Object other) => identical(this, other) || other is Tag && + other.id == id && + other.name == name; + + @override + int get hashCode => + id.hashCode + + name.hashCode; + + @override + String toString() => 'Tag[id=$id, name=$name]'; Map toJson() { final json = {}; @@ -69,19 +55,6 @@ class Tag { return json; } - @override - String toString() => 'Tag[id=$id, name=$name]'; - - @override - bool operator ==(Object other) => identical(this, other) || other is Tag && - other.id == id && - other.name == name; - - @override - int get hashCode => - id.hashCode + - name.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] 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 784f8960f22f..a371d098bbd4 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 @@ -22,13 +22,8 @@ class User { this.userStatus, }); - - int id; - - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. + /// 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']; @@ -42,369 +37,54 @@ class User { } } - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + + int id; String username; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - String firstName; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - String lastName; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - String email; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - String password; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } - - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; - String phone; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } - - Map toJson() { - final json = {}; - if (id != null) { - json['id'] = id; - } - if (username != null) { - json['username'] = username; - } - if (firstName != null) { - json['firstName'] = firstName; - } - if (lastName != null) { - json['lastName'] = lastName; - } - if (email != null) { - json['email'] = email; - } - if (password != null) { - json['password'] = password; - } - if (phone != null) { - json['phone'] = phone; - } - if (userStatus != null) { - json['userStatus'] = userStatus; - } - return json; - } + /// User Status + int userStatus; @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; + 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; - /// User Status - int userStatus; + @override + int get hashCode => + id.hashCode + + username.hashCode + + firstName.hashCode + + lastName.hashCode + + email.hashCode + + password.hashCode + + phone.hashCode + + userStatus.hashCode; - /// Returns a new [User] instance. - /// - /// If [json] [Map] is non-null, its keys and values are mapped to - /// [User]'s properties. - 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']; - } - } + @override + String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; Map toJson() { final json = {}; @@ -435,31 +115,6 @@ class User { return json; } - @override - String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$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 - int get hashCode => - id.hashCode + - username.hashCode + - firstName.hashCode + - lastName.hashCode + - email.hashCode + - password.hashCode + - phone.hashCode + - userStatus.hashCode; - static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] From 412df35d2b880cb5ef885860b629c0f595a21686 Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Tue, 6 Oct 2020 18:03:14 +0200 Subject: [PATCH 18/19] Fix Dart documentation in API classes. --- .../src/main/resources/dart2/api.mustache | 71 +++++++- .../petstore_client_lib/lib/api/pet_api.dart | 159 +++++++++++++----- .../lib/api/store_api.dart | 64 ++++--- .../petstore_client_lib/lib/api/user_api.dart | 134 +++++++++++---- 4 files changed, 321 insertions(+), 107 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 9f2ff8cca348..8bff5b93f832 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -8,11 +8,47 @@ class {{{classname}}} { final ApiClient apiClient; {{#operation}} - /// {{{summary}}} with HTTP info returned. + {{#summary}} + /// {{{summary}}} + {{/summary}} {{#notes}} + {{#summary}} /// - /// {{{notes}}}. + {{/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}} @@ -94,19 +130,36 @@ class {{{classname}}} { ); } - /// {{{summary}}}. - {{#allParams}} + {{#summary}} + /// {{{summary}}} + {{/summary}} + {{#notes}} + {{#summary}} + /// + {{/summary}} + /// {{{notes}}} + {{/notes}} + {{#hasParams}} + {{#summary}} + /// + {{/summary}} + {{^summary}} + {{#notes}} /// + {{/notes}} + {{/summary}} /// Parameters: - /// * {{{dataType}}} {{{paramName}}} {{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}: + /// + {{/hasParams}} + {{#allParams}} + /// * [{{{dataType}}}] {{{paramName}}}{{#required}} (required){{/required}}{{#optional}} (optional){{/optional}}: {{#description}} /// {{{description}}} {{/description}} - {{/allParams}} - {{#notes}} + {{#hasMore}} /// - /// {{{notes}}}. - {{/notes}} + {{/hasMore}} + {{/allParams}} {{#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) { 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 3e25f922ba8d..f9c627fca053 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 @@ -15,7 +15,14 @@ class PetApi { final ApiClient apiClient; - /// Add a new pet to the store with HTTP info returned. + /// 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 { // Verify required params are set. if (body == null) { @@ -59,10 +66,11 @@ class PetApi { ); } - /// Add a new pet to the store. + /// Add a new pet to the store /// /// Parameters: - /// * Pet body (required): + /// + /// * [Pet] body (required): /// Pet object that needs to be added to the store Future addPet(Pet body) async { final response = await addPetWithHttpInfo(body); @@ -74,7 +82,16 @@ class PetApi { 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 { // Verify required params are set. if (petId == null) { @@ -119,14 +136,14 @@ class PetApi { ); } - /// Deletes a pet. + /// Deletes a pet /// /// Parameters: - /// * int petId (required): + /// + /// * [int] petId (required): /// Pet id to delete /// - /// Parameters: - /// * String apiKey : + /// * [String] apiKey: Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= 400) { @@ -137,9 +154,16 @@ class PetApi { 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: /// - /// Multiple status values can be provided with comma separated strings. + /// * [List] status (required): + /// Status values that need to be considered for filter Future findPetsByStatusWithHttpInfo(List status) async { // Verify required params are set. if (status == null) { @@ -184,13 +208,14 @@ class PetApi { ); } - /// Finds Pets by status. + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma separated strings /// /// Parameters: - /// * List status (required): - /// Status values that need to be considered for filter /// - /// Multiple status values can be provided with comma separated strings. + /// * [List] status (required): + /// Status values that need to be considered for filter Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= 400) { @@ -204,9 +229,16 @@ class PetApi { 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: /// - /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.. + /// * [List] tags (required): + /// Tags to filter by Future findPetsByTagsWithHttpInfo(List tags) async { // Verify required params are set. if (tags == null) { @@ -251,13 +283,14 @@ class PetApi { ); } - /// Finds Pets by tags. + /// Finds Pets by tags + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// Parameters: - /// * List tags (required): - /// Tags to filter by /// - /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.. + /// * [List] tags (required): + /// Tags to filter by Future> findPetsByTags(List tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= 400) { @@ -271,9 +304,16 @@ class PetApi { 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: /// - /// Returns a single pet. + /// * [int] petId (required): + /// ID of pet to return Future getPetByIdWithHttpInfo(int petId) async { // Verify required params are set. if (petId == null) { @@ -317,13 +357,14 @@ class PetApi { ); } - /// Find pet by ID. + /// Find pet by ID + /// + /// Returns a single pet /// /// Parameters: - /// * int petId (required): - /// ID of pet to return /// - /// Returns a single pet. + /// * [int] petId (required): + /// ID of pet to return Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= 400) { @@ -335,7 +376,14 @@ class PetApi { 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 { // Verify required params are set. if (body == null) { @@ -379,10 +427,11 @@ class PetApi { ); } - /// Update an existing pet. + /// Update an existing pet /// /// Parameters: - /// * Pet body (required): + /// + /// * [Pet] body (required): /// Pet object that needs to be added to the store Future updatePet(Pet body) async { final response = await updatePetWithHttpInfo(body); @@ -394,7 +443,20 @@ class PetApi { 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 { // Verify required params are set. if (petId == null) { @@ -452,18 +514,17 @@ class PetApi { ); } - /// Updates a pet in the store with form data. + /// Updates a pet in the store with form data /// /// Parameters: - /// * int petId (required): + /// + /// * [int] petId (required): /// ID of pet that needs to be updated /// - /// Parameters: - /// * String name : + /// * [String] name: /// Updated name of the pet /// - /// Parameters: - /// * String status : + /// * [String] status: /// Updated status of the pet Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); @@ -475,7 +536,20 @@ class PetApi { 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 { // Verify required params are set. if (petId == null) { @@ -531,18 +605,17 @@ class PetApi { ); } - /// uploads an image. + /// uploads an image /// /// Parameters: - /// * int petId (required): + /// + /// * [int] petId (required): /// ID of pet to update /// - /// Parameters: - /// * String additionalMetadata : + /// * [String] additionalMetadata: /// Additional data to pass to server /// - /// Parameters: - /// * MultipartFile file : + /// * [MultipartFile] file: /// file to upload Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); 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 85bfc6526e7c..4f65e3ec74e8 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 @@ -15,9 +15,16 @@ class StoreApi { final ApiClient apiClient; - /// Delete purchase order by ID with HTTP info returned. + /// Delete purchase order by ID /// - /// 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 + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [String] orderId (required): + /// ID of the order that needs to be deleted Future deleteOrderWithHttpInfo(String orderId) async { // Verify required params are set. if (orderId == null) { @@ -61,13 +68,14 @@ class StoreApi { ); } - /// Delete purchase order by ID. + /// Delete purchase order by ID + /// + /// 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 /// - /// 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 deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= 400) { @@ -78,9 +86,11 @@ class StoreApi { return; } - /// Returns pet inventories by status with HTTP info returned. + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities /// - /// Returns a map of status codes to quantities. + /// Note: This method returns the HTTP [Response]. Future getInventoryWithHttpInfo() async { // Verify required params are set. @@ -121,9 +131,9 @@ class StoreApi { ); } - /// Returns pet inventories by status. + /// Returns pet inventories by status /// - /// Returns a map of status codes to quantities. + /// Returns a map of status codes to quantities Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= 400) { @@ -135,9 +145,16 @@ class StoreApi { 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. + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [int] orderId (required): + /// ID of pet that needs to be fetched Future getOrderByIdWithHttpInfo(int orderId) async { // Verify required params are set. if (orderId == null) { @@ -181,13 +198,14 @@ class StoreApi { ); } - /// Find purchase order by ID. + /// Find purchase order by ID + /// + /// 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 /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions. + /// * [int] orderId (required): + /// ID of pet that needs to be fetched Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= 400) { @@ -199,7 +217,14 @@ class StoreApi { 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 { // Verify required params are set. if (body == null) { @@ -243,10 +268,11 @@ class StoreApi { ); } - /// Place an order for a pet. + /// Place an order for a pet /// /// Parameters: - /// * Order body (required): + /// + /// * [Order] body (required): /// order placed for purchasing the pet Future placeOrder(Order body) async { final response = await placeOrderWithHttpInfo(body); 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 4f464b488680..a6fae6127080 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 @@ -15,9 +15,16 @@ class UserApi { final ApiClient apiClient; - /// Create user with HTTP info returned. + /// Create user /// - /// This can only be done by the logged in 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 { // Verify required params are set. if (body == null) { @@ -61,13 +68,14 @@ class UserApi { ); } - /// Create user. + /// Create user + /// + /// This can only be done by the logged in user. /// /// Parameters: - /// * User body (required): - /// Created user object /// - /// This can only be done by the logged in user.. + /// * [User] body (required): + /// Created user object Future createUser(User body) async { final response = await createUserWithHttpInfo(body); if (response.statusCode >= 400) { @@ -78,7 +86,14 @@ class UserApi { 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 { // Verify required params are set. if (body == null) { @@ -122,10 +137,11 @@ class UserApi { ); } - /// Creates list of users with given input array. + /// Creates list of users with given input array /// /// Parameters: - /// * List body (required): + /// + /// * [List] body (required): /// List of user object Future createUsersWithArrayInput(List body) async { final response = await createUsersWithArrayInputWithHttpInfo(body); @@ -137,7 +153,14 @@ class UserApi { 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 { // Verify required params are set. if (body == null) { @@ -181,10 +204,11 @@ class UserApi { ); } - /// Creates list of users with given input array. + /// Creates list of users with given input array /// /// Parameters: - /// * List body (required): + /// + /// * [List] body (required): /// List of user object Future createUsersWithListInput(List body) async { final response = await createUsersWithListInputWithHttpInfo(body); @@ -196,9 +220,16 @@ class UserApi { return; } - /// Delete user with HTTP info returned. + /// Delete user + /// + /// This can only be done by the logged in 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 { // Verify required params are set. if (username == null) { @@ -242,13 +273,14 @@ class UserApi { ); } - /// Delete user. + /// Delete user + /// + /// This can only be done by the logged in user. /// /// Parameters: - /// * String username (required): - /// The name that needs to be deleted /// - /// This can only be done by the logged in user.. + /// * [String] username (required): + /// The name that needs to be deleted Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= 400) { @@ -259,7 +291,14 @@ class UserApi { 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 { // Verify required params are set. if (username == null) { @@ -303,10 +342,11 @@ class UserApi { ); } - /// Get user by user name. + /// Get user by user name /// /// Parameters: - /// * String username (required): + /// + /// * [String] username (required): /// The name that needs to be fetched. Use user1 for testing. Future getUserByName(String username) async { final response = await getUserByNameWithHttpInfo(username); @@ -319,7 +359,17 @@ class UserApi { 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 { // Verify required params are set. if (username == null) { @@ -368,14 +418,14 @@ class UserApi { ); } - /// Logs user into the system. + /// Logs user into the system /// /// Parameters: - /// * String username (required): + /// + /// * [String] username (required): /// The user name for login /// - /// Parameters: - /// * String password (required): + /// * [String] password (required): /// The password for login in clear text Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); @@ -388,7 +438,9 @@ class UserApi { 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 { // Verify required params are set. @@ -429,7 +481,7 @@ class UserApi { ); } - /// Logs out current logged in user session. + /// Logs out current logged in user session Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= 400) { @@ -440,9 +492,19 @@ class UserApi { 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]. /// - /// 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 updateUserWithHttpInfo(String username, User body) async { // Verify required params are set. if (username == null) { @@ -489,17 +551,17 @@ class UserApi { ); } - /// Updated user. + /// Updated user + /// + /// This can only be done by the logged in user. /// /// Parameters: - /// * String username (required): + /// + /// * [String] username (required): /// name that need to be deleted /// - /// Parameters: - /// * User body (required): + /// * [User] body (required): /// Updated user object - /// - /// This can only be done by the logged in user.. Future updateUser(String username, User body) async { final response = await updateUserWithHttpInfo(username, body); if (response.statusCode >= 400) { From c1878668cc17ee65249a94759eeb76882b3c575a Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Tue, 6 Oct 2020 19:11:00 +0200 Subject: [PATCH 19/19] Simplify test in HTTP Basic auth, remove unused lint rule. --- .../src/main/resources/dart2/auth/header.mustache | 2 +- .../src/main/resources/dart2/auth/http_basic_auth.mustache | 4 ++-- .../src/main/resources/dart2/header.mustache | 2 +- .../client/petstore/dart2/petstore_client_lib/lib/api.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/api/pet_api.dart | 2 +- .../dart2/petstore_client_lib/lib/api/store_api.dart | 2 +- .../dart2/petstore_client_lib/lib/api/user_api.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/api_client.dart | 2 +- .../dart2/petstore_client_lib/lib/api_exception.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/api_helper.dart | 2 +- .../dart2/petstore_client_lib/lib/auth/api_key_auth.dart | 2 +- .../dart2/petstore_client_lib/lib/auth/authentication.dart | 2 +- .../dart2/petstore_client_lib/lib/auth/http_basic_auth.dart | 6 +++--- .../petstore_client_lib/lib/auth/http_bearer_auth.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/auth/oauth.dart | 2 +- .../dart2/petstore_client_lib/lib/model/api_response.dart | 2 +- .../dart2/petstore_client_lib/lib/model/category.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/model/order.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/model/pet.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/model/tag.dart | 2 +- .../petstore/dart2/petstore_client_lib/lib/model/user.dart | 2 +- 21 files changed, 24 insertions(+), 24 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache index 15c11556cedb..db48248792a9 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache @@ -5,4 +5,4 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// 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 4017bba38643..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 @@ -6,7 +6,7 @@ class HttpBasicAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final 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))}'; } } diff --git a/modules/openapi-generator/src/main/resources/dart2/header.mustache b/modules/openapi-generator/src/main/resources/dart2/header.mustache index 15c11556cedb..db48248792a9 100644 --- a/modules/openapi-generator/src/main/resources/dart2/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/header.mustache @@ -5,4 +5,4 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars 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 0c5ef06b0a67..5fa4f759553d 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars library openapi.api; 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 f9c627fca053..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 4f65e3ec74e8..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 a6fae6127080..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 7ac29d8b28ff..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 7567f9064322..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 e3236e175813..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 5189648aa096..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 98b0a1effe32..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 b8390b31bfce..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; @@ -15,7 +15,7 @@ class HttpBasicAuth implements Authentication { @override void applyToParams(List queryParams, Map headerParams) { - final 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))}'; } } 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 aa991105181f..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 2dbfa61af324..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 97dfbc13c6d8..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 0d58f0627080..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 25dda095b85b..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 53704e252116..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 1b12e0194b5b..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api; 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 a371d098bbd4..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 @@ -5,7 +5,7 @@ // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first -// ignore_for_file: avoid_init_to_null, lines_longer_than_80_chars +// ignore_for_file: lines_longer_than_80_chars part of openapi.api;