From 26ca6ab27efb31b59f37d8b9bb50cb495d4c236e Mon Sep 17 00:00:00 2001 From: Noor Dawod Date: Wed, 31 Mar 2021 17:53:22 +0200 Subject: [PATCH] [Dart2] Add initial support to use an isolate to offload JSON serialization/deserialization (#9100) * Change signature of deserialize() to be a Future. * Grammar tlc for a couple of sentences. * Make serialize() use a Future also. * Add useCompute as a parameter to ApiClient, adjust to use compute when serializing/deserializing. * Updated Pet Store client code. * Ordered imports. * Remove Flutter-specific implementation. * Rename global functions to serialize/deserialize JSON. * Fix return type for apiClientSerialize. * Updated pet store client code. * Remove remark for _deserialize. * Make _decodeBodyBytes a Future function. * Updated pet store client code. * Use await when calling serialize(). * Fix a grammatical error. * Adjust doc. * Centralize deserialization code in one function. * Updated pet store client code. * Add await to serialize() in few more tests. * Make output look better for linting and humans. * Updated pet store code. * Add an empty line. * Updated pet store code. * Call the right serializer. * Reuse same variable. * Updated pet store code. * Fix a logical error when deserializing. * Calculate growable once. * Ignore reassignment. * Adjust a test. * Regenerate petstore code. * Revert back previous test. * Use serialize() for testing. * Revert using serialize() for testing. * Add removal deprecation for serialize/deserialize. * Updated petstore code. * Updated deprecation note. * Adjust tests to wait for futures. --- .../src/main/resources/dart2/api.mustache | 8 +- .../main/resources/dart2/api_client.mustache | 131 +++++++++++------ .../main/resources/dart2/api_helper.mustache | 2 +- .../src/main/resources/dart2/apilib.mustache | 3 +- .../petstore/test/pet_faked_client_test.dart | 67 +++++---- .../dart2/petstore/test/pet_test.dart | 22 ++- .../test/store_faked_client_test.dart | 10 +- .../petstore/test/user_faked_client_test.dart | 36 ++--- .../dart2/petstore_client_lib/lib/api.dart | 1 - .../petstore_client_lib/lib/api/pet_api.dart | 24 ++-- .../lib/api/store_api.dart | 14 +- .../petstore_client_lib/lib/api/user_api.dart | 20 +-- .../petstore_client_lib/lib/api_client.dart | 133 ++++++++++++------ .../petstore_client_lib/lib/api_helper.dart | 2 +- .../petstore/test/pet_faked_client_test.dart | 83 ++++++----- .../dart2/petstore/test/pet_test.dart | 22 ++- .../test/store_faked_client_test.dart | 10 +- .../petstore/test/user_faked_client_test.dart | 48 ++++--- .../dart2/petstore_client_lib/lib/api.dart | 1 - .../petstore_client_lib/lib/api/pet_api.dart | 28 ++-- .../lib/api/store_api.dart | 14 +- .../petstore_client_lib/lib/api/user_api.dart | 20 +-- .../petstore_client_lib/lib/api_client.dart | 133 ++++++++++++------ .../petstore_client_lib/lib/api_helper.dart | 2 +- .../petstore_client_lib_fake/lib/api.dart | 1 - .../lib/api/another_fake_api.dart | 4 +- .../lib/api/default_api.dart | 4 +- .../lib/api/fake_api.dart | 46 +++--- .../lib/api/fake_classname_tags123_api.dart | 4 +- .../lib/api/pet_api.dart | 28 ++-- .../lib/api/store_api.dart | 14 +- .../lib/api/user_api.dart | 20 +-- .../lib/api_client.dart | 133 ++++++++++++------ .../lib/api_helper.dart | 2 +- .../lib/api.dart | 3 +- .../lib/api/another_fake_api.dart | 2 +- .../lib/api/default_api.dart | 2 +- .../lib/api/fake_api.dart | 32 ++--- .../lib/api/fake_classname_tags123_api.dart | 2 +- .../lib/api/pet_api.dart | 18 +-- .../lib/api/store_api.dart | 8 +- .../lib/api/user_api.dart | 16 +-- .../lib/api_client.dart | 22 +-- .../lib/api_helper.dart | 2 +- 44 files changed, 700 insertions(+), 497 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 61ecab963b6..d99ba2b325f 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -178,7 +178,7 @@ class {{{classname}}} { Future<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{{nickname}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { final response = await {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}} {{#allParams}}{{^required}}{{{paramName}}}: {{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}} {{/hasOptionalParams}}); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } {{#returnType}} // When a remote server returns no body with a status of 204, we shall not decode it. @@ -187,16 +187,16 @@ class {{{classname}}} { if (response.body != null && response.statusCode != HttpStatus.noContent) { {{#native_serialization}} {{#isArray}} - return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), '{{{returnType}}}') as List) .cast<{{{returnBaseType}}}>() .{{#uniqueItems}}toSet(){{/uniqueItems}}{{^uniqueItems}}toList(growable: false){{/uniqueItems}}; {{/isArray}} {{^isArray}} {{#isMap}} - return {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}')); + return {{{returnType}}}.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), '{{{returnType}}}'),); {{/isMap}} {{^isMap}} - return apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as {{{returnType}}}; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), '{{{returnType}}}',) as {{{returnType}}}; {{/isMap}}{{/isArray}}{{/native_serialization}}{{#json_serializable}} {{#isArray}} {{#uniqueItems}} 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 a5d3b0948e7..167b6951e01 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -51,17 +51,16 @@ class ApiClient { Map get defaultHeaderMap => _defaultHeaderMap; - /// returns an unmodifiable view of the authentications, since none should be added - /// nor deleted - Map get authentications => - Map.unmodifiable(_authentications); + /// Returns an unmodifiable [Map] of the authentications, since none should be added + /// or deleted. + Map get authentications => Map.unmodifiable(_authentications); T getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } - // We don’t use a Map for queryParams. + // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, @@ -92,7 +91,7 @@ class ApiClient { } try { - // Special case for uploading a single file which isn’t a 'multipart/form-data'. + // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) @@ -122,7 +121,7 @@ class ApiClient { final msgBody = nullableContentType == 'application/x-www-form-urlencoded' ? formParams - : serialize(body); + : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { @@ -147,9 +146,48 @@ class ApiClient { throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); } +{{#native_serialization}} + + Future deserializeAsync(String json, String targetType, {bool growable}) async => + // ignore: deprecated_member_use_from_same_package + deserialize(json, targetType, growable: growable); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') + dynamic deserialize(String json, String targetType, {bool growable}) { + // Remove all spaces. Necessary for regular expressions as well. + targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: growable == true); + } +{{/native_serialization}} + + // ignore: deprecated_member_use_from_same_package + Future serializeAsync(Object value) async => serialize(value); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') + String serialize(Object value) => value == null ? '' : json.encode(value); + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { + authNames.forEach((authName) { + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } + auth.applyToParams(queryParams, headerParams); + }); + } {{#native_serialization}} - dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { try { switch (targetType) { case 'String': @@ -180,57 +218,68 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) - .toList(growable: true == growable); + .map((v) => _deserialize(v, targetType, growable: growable)) + .toList(growable: growable); } if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) + .map((v) => _deserialize(v, targetType, growable: growable)) .toSet(); } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return Map.fromIterables( value.keys, - value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + value.values.map((v) => _deserialize(v, targetType, growable: growable)), ); } break; } - } on Exception catch (e, stack) { - throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', e, stack,); + } catch (error, trace) { + throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,); } throw ApiException(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',); } +{{/native_serialization}} +} +{{#native_serialization}} - dynamic deserialize(String json, String targetType, {bool growable}) { - // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(' ', ''); +/// Primarily intended for use in an isolate. +class DeserializationMessage { + const DeserializationMessage({ + @required this.json, + @required this.targetType, + this.growable, + }); + /// The JSON value to deserialize. + final String json; + + /// Target type to deserialize to. + final String targetType; + + /// Whether to make deserialized lists or maps growable. + final bool growable; +} + +/// Primarily intended for use in an isolate. +Future deserializeAsync(DeserializationMessage message) async { + // Remove all spaces. Necessary for regular expressions as well. + final targetType = message.targetType.replaceAll(' ', ''); + + // If the expected target type is String, nothing to do... return targetType == 'String' - ? json - : _deserialize(jsonDecode(json), targetType, growable: true == growable); - } + ? message.json + : ApiClient._deserialize( + jsonDecode(message.json), + targetType, + growable: message.growable == true, + ); +} {{/native_serialization}} - String serialize(Object obj) => obj == null ? '' : json.encode(obj); - - /// Update query and header parameters based on authentication settings. - /// @param authNames The authentications to apply - void _updateParamsForAuth( - List authNames, - List queryParams, - Map headerParams, - ) { - authNames.forEach((authName) { - final auth = _authentications[authName]; - if (auth == null) { - throw ArgumentError('Authentication undefined: $authName'); - } - auth.applyToParams(queryParams, headerParams); - }); - } -} +/// Primarily intended for use in an isolate. +Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); 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 8e70b9920bf..92f394176f6 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache @@ -63,7 +63,7 @@ String parameterToString(dynamic value) { /// 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) { +Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) diff --git a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache index e17f4ed139a..df10d804011 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -7,11 +7,10 @@ import 'dart:io'; import 'package:http/http.dart'; import 'package:intl/intl.dart'; - -import 'package:meta/meta.dart'; {{#json_serializable}} import 'package:json_annotation/json_annotation.dart'; {{/json_serializable}} +import 'package:meta/meta.dart'; part 'api_client.dart'; part 'api_helper.dart'; diff --git a/samples/client/petstore/dart2/petstore/test/pet_faked_client_test.dart b/samples/client/petstore/dart2/petstore/test/pet_faked_client_test.dart index 0b80d597c6c..7d18af8762b 100644 --- a/samples/client/petstore/dart2/petstore/test/pet_faked_client_test.dart +++ b/samples/client/petstore/dart2/petstore/test/pet_faked_client_test.dart @@ -39,7 +39,7 @@ void main() { Future addPet(Pet pet) { petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(pet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(pet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); return petApi.addPet(pet); @@ -53,7 +53,8 @@ void main() { // use the pet api to add a pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -61,7 +62,7 @@ void main() { // retrieve the same pet by id petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(newPet), + getResponseBody: await petApi.apiClient.serializeAsync(newPet), ); final retrievedPet = await petApi.getPetById(id); @@ -86,7 +87,8 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -115,7 +117,8 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -139,7 +142,7 @@ void main() { newPet.name = 'Doge'; petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(newPet), + getResponseBody: await petApi.apiClient.serializeAsync(newPet), ); final pet = await petApi.getPetById(id); expect(pet.name, equals('Doge')); @@ -154,7 +157,8 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -162,7 +166,8 @@ void main() { // update the same pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPutRequestBody: petApi.apiClient.serialize(updatePet), + expectedPutRequestBody: + await petApi.apiClient.serializeAsync(updatePet), putResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.updatePet(updatePet); @@ -170,7 +175,7 @@ void main() { // check update worked petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(updatePet), + getResponseBody: await petApi.apiClient.serializeAsync(updatePet), ); final pet = await petApi.getPetById(id); expect(pet.name, equals(name)); @@ -180,30 +185,31 @@ void main() { final id1 = newId(); final id2 = newId(); final id3 = newId(); - final status = PetStatusEnum.available.value; + final status = '${PetStatusEnum.available}'; final pet1 = makePet(id: id1, status: status); final pet2 = makePet(id: id2, status: status); - final pet3 = makePet(id: id3, status: PetStatusEnum.sold.value); + final pet3 = makePet(id: id3, status: '${PetStatusEnum.sold}'); - return Future.wait([addPet(pet1), addPet(pet2), addPet(pet3)]) - .then((_) async { - // retrieve pets by status - petApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', - getResponseBody: petApi.apiClient.serialize([pet1, pet2]), - ); - final pets = await petApi.findPetsByStatus([status]); + await addPet(pet1); + await addPet(pet2); + await addPet(pet3); - // tests serialisation and deserialisation of enum - final petsByStatus = - pets.where((p) => p.status == PetStatusEnum.available); - expect(petsByStatus.length, equals(2)); - final petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); + // retrieve pets by status + petApi.apiClient.client = FakeClient( + expectedUrl: + 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', + getResponseBody: await petApi.apiClient.serializeAsync([pet1, pet2]), + ); + final pets = await petApi.findPetsByStatus([status]); + + // tests serialisation and deserialisation of enum + final petsByStatus = + pets.where((p) => p.status == PetStatusEnum.available); + expect(petsByStatus.length, equals(2)); + final petIds = pets.map((pet) => pet.id).toList(); + expect(petIds, contains(id1)); + expect(petIds, contains(id2)); + expect(petIds, isNot(contains(id3))); }); test('uploads a pet image', () async { @@ -216,7 +222,8 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), postResponseBody: '', expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); diff --git a/samples/client/petstore/dart2/petstore/test/pet_test.dart b/samples/client/petstore/dart2/petstore/test/pet_test.dart index e480ec7baa0..72126ba6a90 100644 --- a/samples/client/petstore/dart2/petstore/test/pet_test.dart +++ b/samples/client/petstore/dart2/petstore/test/pet_test.dart @@ -81,19 +81,17 @@ void main() { var id1 = newId(); var id2 = newId(); var id3 = newId(); - var status = PetStatusEnum.available.value; + var status = '${PetStatusEnum.available}'; - return Future.wait([ - petApi.addPet(makePet(id: id1, status: status)), - petApi.addPet(makePet(id: id2, status: status)), - petApi.addPet(makePet(id: id3, status: PetStatusEnum.sold.value)) - ]).then((_) async { - var pets = await petApi.findPetsByStatus([status]); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); + await petApi.addPet(makePet(id: id1, status: status)); + await petApi.addPet(makePet(id: id2, status: status)); + await petApi.addPet(makePet(id: id3, status: '${PetStatusEnum.sold}')); + + var pets = await petApi.findPetsByStatus([status]); + var petIds = pets.map((pet) => pet.id).toList(); + expect(petIds, contains(id1)); + expect(petIds, contains(id2)); + expect(petIds, isNot(contains(id3))); }); test('uploads a pet image', () async { diff --git a/samples/client/petstore/dart2/petstore/test/store_faked_client_test.dart b/samples/client/petstore/dart2/petstore/test/store_faked_client_test.dart index 5ebdc63861d..9f75fd55d86 100644 --- a/samples/client/petstore/dart2/petstore/test/store_faked_client_test.dart +++ b/samples/client/petstore/dart2/petstore/test/store_faked_client_test.dart @@ -28,8 +28,8 @@ void main() { // // use the store api to add an order // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: storeApi.apiClient.serialize(newOrder), - // postResponseBody: storeApi.apiClient.serialize(newOrder), + // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // expectedHeaders: {"Content-Type": "application/json"} // ); // await storeApi.placeOrder(newOrder); @@ -37,7 +37,7 @@ void main() { // // retrieve the same order by id // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // getResponseBody: storeApi.apiClient.serialize(newOrder), + // getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // ); // final placedOrder = await storeApi.getOrderById(id); // expect(placedOrder.id, equals(id)); @@ -51,8 +51,8 @@ void main() { // // use the store api to add an order // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: storeApi.apiClient.serialize(newOrder), - // postResponseBody: storeApi.apiClient.serialize(newOrder), + // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // expectedHeaders: {"Content-Type": "application/json"} // ); // await storeApi.placeOrder(newOrder); diff --git a/samples/client/petstore/dart2/petstore/test/user_faked_client_test.dart b/samples/client/petstore/dart2/petstore/test/user_faked_client_test.dart index df2b4686f13..53cc659a8f2 100644 --- a/samples/client/petstore/dart2/petstore/test/user_faked_client_test.dart +++ b/samples/client/petstore/dart2/petstore/test/user_faked_client_test.dart @@ -29,15 +29,16 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); // retrieve the same user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/$username', - getResponseBody: userApi.apiClient.serialize(newUser), + getResponseBody: await userApi.apiClient.serializeAsync(newUser), ); var user = await userApi.getUserByName(username); expect(user.id, equals(id)); @@ -58,8 +59,8 @@ void main() { // use the user api to create a list of users userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/createWithList', - expectedPostRequestBody: userApi.apiClient.serialize(users), - postResponseBody: userApi.apiClient.serialize(users), + expectedPostRequestBody: await userApi.apiClient.serializeAsync(users), + postResponseBody: await userApi.apiClient.serializeAsync(users), ); await userApi.createUsersWithListInput(users); @@ -67,7 +68,7 @@ void main() { userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${users.elementAt(0).username}', - getResponseBody: userApi.apiClient.serialize( + getResponseBody: await userApi.apiClient.serializeAsync( users.elementAt(0), ), ); @@ -75,7 +76,7 @@ void main() { userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${users.elementAt(1).username}', - getResponseBody: userApi.apiClient.serialize( + getResponseBody: await userApi.apiClient.serializeAsync( users.elementAt(1), ), ); @@ -92,8 +93,9 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); newUser.email = email; @@ -101,15 +103,15 @@ void main() { // use the user api to update the user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - expectedPutRequestBody: userApi.apiClient.serialize(newUser), - putResponseBody: userApi.apiClient.serialize(newUser), + expectedPutRequestBody: await userApi.apiClient.serializeAsync(newUser), + putResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.updateUser(username, newUser); // retrieve the same user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - getResponseBody: userApi.apiClient.serialize(newUser), + getResponseBody: await userApi.apiClient.serializeAsync(newUser), ); var foundUser = await userApi.getUserByName(username); expect(foundUser.email, equals(email)); @@ -122,8 +124,9 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); @@ -152,8 +155,9 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); 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 ba25916af59..f6bf3e75908 100644 --- a/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -15,7 +15,6 @@ import 'dart:io'; import 'package:http/http.dart'; import 'package:intl/intl.dart'; - import 'package:meta/meta.dart'; part 'api_client.dart'; 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 c6446b85653..b38cbce1d3a 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 @@ -74,7 +74,7 @@ class PetApi { Future addPet(Pet body) async { final response = await addPetWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -146,7 +146,7 @@ class PetApi { Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -215,13 +215,13 @@ class PetApi { Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'List') as List) .cast() .toList(growable: false); } @@ -293,13 +293,13 @@ class PetApi { Future> findPetsByTags(List tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'List') as List) .cast() .toList(growable: false); } @@ -370,13 +370,13 @@ class PetApi { Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } return Future.value(null); } @@ -440,7 +440,7 @@ class PetApi { Future updatePet(Pet body) async { final response = await updatePetWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -530,7 +530,7 @@ class PetApi { Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -618,13 +618,13 @@ class PetApi { Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } return Future.value(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 490860ed8c2..836d4ca8b0b 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 @@ -79,7 +79,7 @@ class StoreApi { Future deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -131,13 +131,13 @@ class StoreApi { Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); + return Map.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Map'),); } return Future>.value(null); } @@ -206,13 +206,13 @@ class StoreApi { Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(null); } @@ -276,13 +276,13 @@ class StoreApi { Future placeOrder(Order body) async { final response = await placeOrderWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(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 f643e2e5dab..93b55fd2c41 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 @@ -78,7 +78,7 @@ class UserApi { Future createUser(User body) async { final response = await createUserWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -141,7 +141,7 @@ class UserApi { Future createUsersWithArrayInput(List body) async { final response = await createUsersWithArrayInputWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -204,7 +204,7 @@ class UserApi { Future createUsersWithListInput(List body) async { final response = await createUsersWithListInputWithHttpInfo(body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -272,7 +272,7 @@ class UserApi { Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -336,13 +336,13 @@ class UserApi { Future getUserByName(String username) async { final response = await getUserByNameWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'User',) as User; } return Future.value(null); } @@ -418,13 +418,13 @@ class UserApi { Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } return Future.value(null); } @@ -473,7 +473,7 @@ class UserApi { Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -550,7 +550,7 @@ class UserApi { Future updateUser(String username, User body) async { final response = await updateUserWithHttpInfo(username, body); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } 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 87a7a36d470..c847d27f60b 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 @@ -44,17 +44,16 @@ class ApiClient { Map get defaultHeaderMap => _defaultHeaderMap; - /// returns an unmodifiable view of the authentications, since none should be added - /// nor deleted - Map get authentications => - Map.unmodifiable(_authentications); + /// Returns an unmodifiable [Map] of the authentications, since none should be added + /// or deleted. + Map get authentications => Map.unmodifiable(_authentications); T getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } - // We don’t use a Map for queryParams. + // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, @@ -85,7 +84,7 @@ class ApiClient { } try { - // Special case for uploading a single file which isn’t a 'multipart/form-data'. + // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) @@ -115,7 +114,7 @@ class ApiClient { final msgBody = nullableContentType == 'application/x-www-form-urlencoded' ? formParams - : serialize(body); + : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { @@ -141,7 +140,44 @@ class ApiClient { throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); } - dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + Future deserializeAsync(String json, String targetType, {bool growable}) async => + // ignore: deprecated_member_use_from_same_package + deserialize(json, targetType, growable: growable); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') + dynamic deserialize(String json, String targetType, {bool growable}) { + // Remove all spaces. Necessary for regular expressions as well. + targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: growable == true); + } + + // ignore: deprecated_member_use_from_same_package + Future serializeAsync(Object value) async => serialize(value); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') + String serialize(Object value) => value == null ? '' : json.encode(value); + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { + authNames.forEach((authName) { + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } + auth.applyToParams(queryParams, headerParams); + }); + } + + static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { try { switch (targetType) { case 'String': @@ -172,56 +208,65 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) - .toList(growable: true == growable); + .map((v) => _deserialize(v, targetType, growable: growable)) + .toList(growable: growable); } if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) + .map((v) => _deserialize(v, targetType, growable: growable)) .toSet(); } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return Map.fromIterables( value.keys, - value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + value.values.map((v) => _deserialize(v, targetType, growable: growable)), ); } break; } - } on Exception catch (e, stack) { - throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', e, stack,); + } catch (error, trace) { + throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,); } throw ApiException(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',); } - - dynamic deserialize(String json, String targetType, {bool growable}) { - // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(' ', ''); - - return targetType == 'String' - ? json - : _deserialize(jsonDecode(json), targetType, growable: true == growable); - } - - String serialize(Object obj) => obj == null ? '' : json.encode(obj); - - /// Update query and header parameters based on authentication settings. - /// @param authNames The authentications to apply - void _updateParamsForAuth( - List authNames, - List queryParams, - Map headerParams, - ) { - authNames.forEach((authName) { - final auth = _authentications[authName]; - if (auth == null) { - throw ArgumentError('Authentication undefined: $authName'); - } - auth.applyToParams(queryParams, headerParams); - }); - } } + +/// Primarily intended for use in an isolate. +class DeserializationMessage { + const DeserializationMessage({ + @required this.json, + @required this.targetType, + this.growable, + }); + + /// The JSON value to deserialize. + final String json; + + /// Target type to deserialize to. + final String targetType; + + /// Whether to make deserialized lists or maps growable. + final bool growable; +} + +/// Primarily intended for use in an isolate. +Future deserializeAsync(DeserializationMessage message) async { + // Remove all spaces. Necessary for regular expressions as well. + final targetType = message.targetType.replaceAll(' ', ''); + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? message.json + : ApiClient._deserialize( + jsonDecode(message.json), + targetType, + growable: message.growable == true, + ); +} + +/// Primarily intended for use in an isolate. +Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); 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 141f4a7f5b4..4135dcf95b2 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 @@ -63,7 +63,7 @@ String parameterToString(dynamic value) { /// 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) { +Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart index 70f1b0d6beb..277c49b3971 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart @@ -36,11 +36,11 @@ void main() { } /// Setup the fake client then call [petApi.addPet] - Future addPet(Pet pet) { + Future addPet(Pet pet) async { petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(pet), - postResponseBody: petApi.apiClient.serialize(pet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(pet), + postResponseBody: await petApi.apiClient.serializeAsync(pet), expectedHeaders: {'Content-Type': 'application/json'}); return petApi.addPet(pet); } @@ -53,15 +53,16 @@ void main() { // use the pet api to add a pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), - postResponseBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), + postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); // retrieve the same pet by id petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(newPet), + getResponseBody: await petApi.apiClient.serializeAsync(newPet), ); final retrievedPet = await petApi.getPetById(id); @@ -86,8 +87,9 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), - postResponseBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), + postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -115,8 +117,9 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), - postResponseBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), + postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -139,7 +142,7 @@ void main() { newPet.name = 'Doge'; petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(newPet), + getResponseBody: await petApi.apiClient.serializeAsync(newPet), ); final pet = await petApi.getPetById(id); expect(pet.name, equals('Doge')); @@ -154,23 +157,25 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), - postResponseBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), + postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); // update the same pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPutRequestBody: petApi.apiClient.serialize(updatePet), - putResponseBody: petApi.apiClient.serialize(updatePet), + expectedPutRequestBody: + await petApi.apiClient.serializeAsync(updatePet), + putResponseBody: await petApi.apiClient.serializeAsync(updatePet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.updatePet(updatePet); // check update worked petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: petApi.apiClient.serialize(updatePet), + getResponseBody: await petApi.apiClient.serializeAsync(updatePet), ); final pet = await petApi.getPetById(id); expect(pet.name, equals(name)); @@ -180,30 +185,31 @@ void main() { final id1 = newId(); final id2 = newId(); final id3 = newId(); - final status = PetStatusEnum.available.value; + final status = '${PetStatusEnum.available}'; final pet1 = makePet(id: id1, status: status); final pet2 = makePet(id: id2, status: status); - final pet3 = makePet(id: id3, status: PetStatusEnum.sold.value); + final pet3 = makePet(id: id3, status: '${PetStatusEnum.sold}'); - return Future.wait([addPet(pet1), addPet(pet2), addPet(pet3)]) - .then((_) async { - // retrieve pets by status - petApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', - getResponseBody: petApi.apiClient.serialize([pet1, pet2]), - ); - final pets = await petApi.findPetsByStatus([status]); + await addPet(pet1); + await addPet(pet2); + await addPet(pet3); - // tests serialisation and deserialisation of enum - final petsByStatus = - pets.where((p) => p.status == PetStatusEnum.available); - expect(petsByStatus.length, equals(2)); - final petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); + // retrieve pets by status + petApi.apiClient.client = FakeClient( + expectedUrl: + 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', + getResponseBody: await petApi.apiClient.serializeAsync([pet1, pet2]), + ); + final pets = await petApi.findPetsByStatus([status]); + + // tests serialisation and deserialisation of enum + final petsByStatus = + pets.where((p) => p.status == PetStatusEnum.available); + expect(petsByStatus.length, equals(2)); + final petIds = pets.map((pet) => pet.id).toList(); + expect(petIds, contains(id1)); + expect(petIds, contains(id2)); + expect(petIds, isNot(contains(id3))); }); test('uploads a pet image', () async { @@ -216,8 +222,9 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: petApi.apiClient.serialize(newPet), - postResponseBody: petApi.apiClient.serialize(newPet), + expectedPostRequestBody: + await petApi.apiClient.serializeAsync(newPet), + postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart index e480ec7baa0..72126ba6a90 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart @@ -81,19 +81,17 @@ void main() { var id1 = newId(); var id2 = newId(); var id3 = newId(); - var status = PetStatusEnum.available.value; + var status = '${PetStatusEnum.available}'; - return Future.wait([ - petApi.addPet(makePet(id: id1, status: status)), - petApi.addPet(makePet(id: id2, status: status)), - petApi.addPet(makePet(id: id3, status: PetStatusEnum.sold.value)) - ]).then((_) async { - var pets = await petApi.findPetsByStatus([status]); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); + await petApi.addPet(makePet(id: id1, status: status)); + await petApi.addPet(makePet(id: id2, status: status)); + await petApi.addPet(makePet(id: id3, status: '${PetStatusEnum.sold}')); + + var pets = await petApi.findPetsByStatus([status]); + var petIds = pets.map((pet) => pet.id).toList(); + expect(petIds, contains(id1)); + expect(petIds, contains(id2)); + expect(petIds, isNot(contains(id3))); }); test('uploads a pet image', () async { diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart index 5ebdc63861d..9f75fd55d86 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart @@ -28,8 +28,8 @@ void main() { // // use the store api to add an order // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: storeApi.apiClient.serialize(newOrder), - // postResponseBody: storeApi.apiClient.serialize(newOrder), + // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // expectedHeaders: {"Content-Type": "application/json"} // ); // await storeApi.placeOrder(newOrder); @@ -37,7 +37,7 @@ void main() { // // retrieve the same order by id // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // getResponseBody: storeApi.apiClient.serialize(newOrder), + // getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // ); // final placedOrder = await storeApi.getOrderById(id); // expect(placedOrder.id, equals(id)); @@ -51,8 +51,8 @@ void main() { // // use the store api to add an order // storeApi.apiClient.client = FakeClient( // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: storeApi.apiClient.serialize(newOrder), - // postResponseBody: storeApi.apiClient.serialize(newOrder), + // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), // expectedHeaders: {"Content-Type": "application/json"} // ); // await storeApi.placeOrder(newOrder); diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart index 2d549e84fc8..f8137935192 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart @@ -29,16 +29,17 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - expectedHeaders: { 'Content-Type': 'application/json' }, - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + expectedHeaders: {'Content-Type': 'application/json'}, + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); // retrieve the same user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/$username', - getResponseBody: userApi.apiClient.serialize(newUser), + getResponseBody: await userApi.apiClient.serializeAsync(newUser), ); var user = await userApi.getUserByName(username); expect(user.id, equals(id)); @@ -59,9 +60,9 @@ void main() { // use the user api to create a list of users userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/createWithList', - expectedPostRequestBody: userApi.apiClient.serialize(users), - expectedHeaders: { 'Content-Type': 'application/json' }, - postResponseBody: userApi.apiClient.serialize(users), + expectedPostRequestBody: await userApi.apiClient.serializeAsync(users), + expectedHeaders: {'Content-Type': 'application/json'}, + postResponseBody: await userApi.apiClient.serializeAsync(users), ); await userApi.createUsersWithListInput(users); @@ -69,7 +70,7 @@ void main() { userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${users.elementAt(0).username}', - getResponseBody: userApi.apiClient.serialize( + getResponseBody: await userApi.apiClient.serializeAsync( users.elementAt(0), ), ); @@ -77,7 +78,7 @@ void main() { userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${users.elementAt(1).username}', - getResponseBody: userApi.apiClient.serialize( + getResponseBody: await userApi.apiClient.serializeAsync( users.elementAt(1), ), ); @@ -94,9 +95,10 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - expectedHeaders: { 'Content-Type': 'application/json' }, - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + expectedHeaders: {'Content-Type': 'application/json'}, + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); newUser.email = email; @@ -104,16 +106,16 @@ void main() { // use the user api to update the user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - expectedPutRequestBody: userApi.apiClient.serialize(newUser), - expectedHeaders: { 'Content-Type': 'application/json' }, - putResponseBody: userApi.apiClient.serialize(newUser), + expectedPutRequestBody: await userApi.apiClient.serializeAsync(newUser), + expectedHeaders: {'Content-Type': 'application/json'}, + putResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.updateUser(username, newUser); // retrieve the same user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - getResponseBody: userApi.apiClient.serialize(newUser), + getResponseBody: await userApi.apiClient.serializeAsync(newUser), ); var foundUser = await userApi.getUserByName(username); expect(foundUser.email, equals(email)); @@ -126,9 +128,10 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - expectedHeaders: { 'Content-Type': 'application/json' }, - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + expectedHeaders: {'Content-Type': 'application/json'}, + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); @@ -157,9 +160,10 @@ void main() { // use the user api to create a user userApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: userApi.apiClient.serialize(newUser), - expectedHeaders: { 'Content-Type': 'application/json' }, - postResponseBody: userApi.apiClient.serialize(newUser), + expectedPostRequestBody: + await userApi.apiClient.serializeAsync(newUser), + expectedHeaders: {'Content-Type': 'application/json'}, + postResponseBody: await userApi.apiClient.serializeAsync(newUser), ); await userApi.createUser(newUser); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart index ba25916af59..f6bf3e75908 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -15,7 +15,6 @@ import 'dart:io'; import 'package:http/http.dart'; import 'package:intl/intl.dart'; - import 'package:meta/meta.dart'; part 'api_client.dart'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart index 2f9bc586380..2ec34d475e2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart @@ -74,13 +74,13 @@ class PetApi { Future addPet(Pet pet) async { final response = await addPetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } return Future.value(null); } @@ -153,7 +153,7 @@ class PetApi { Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -222,13 +222,13 @@ class PetApi { Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'List') as List) .cast() .toList(growable: false); } @@ -300,13 +300,13 @@ class PetApi { Future> findPetsByTags(List tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'List') as List) .cast() .toList(growable: false); } @@ -377,13 +377,13 @@ class PetApi { Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } return Future.value(null); } @@ -447,13 +447,13 @@ class PetApi { Future updatePet(Pet pet) async { final response = await updatePetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } return Future.value(null); } @@ -544,7 +544,7 @@ class PetApi { Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -632,13 +632,13 @@ class PetApi { Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart index 76ffaec6faa..9696bacc9de 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart @@ -79,7 +79,7 @@ class StoreApi { Future deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -131,13 +131,13 @@ class StoreApi { Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); + return Map.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Map'),); } return Future>.value(null); } @@ -206,13 +206,13 @@ class StoreApi { Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(null); } @@ -276,13 +276,13 @@ class StoreApi { Future placeOrder(Order order) async { final response = await placeOrderWithHttpInfo(order); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart index 08847cc2b07..fc19afb4e93 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart @@ -78,7 +78,7 @@ class UserApi { Future createUser(User user) async { final response = await createUserWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -141,7 +141,7 @@ class UserApi { Future createUsersWithArrayInput(List user) async { final response = await createUsersWithArrayInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -204,7 +204,7 @@ class UserApi { Future createUsersWithListInput(List user) async { final response = await createUsersWithListInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -272,7 +272,7 @@ class UserApi { Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -336,13 +336,13 @@ class UserApi { Future getUserByName(String username) async { final response = await getUserByNameWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'User',) as User; } return Future.value(null); } @@ -418,13 +418,13 @@ class UserApi { Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } return Future.value(null); } @@ -473,7 +473,7 @@ class UserApi { Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -550,7 +550,7 @@ class UserApi { Future updateUser(String username, User user) async { final response = await updateUserWithHttpInfo(username, user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index 87a7a36d470..c847d27f60b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -44,17 +44,16 @@ class ApiClient { Map get defaultHeaderMap => _defaultHeaderMap; - /// returns an unmodifiable view of the authentications, since none should be added - /// nor deleted - Map get authentications => - Map.unmodifiable(_authentications); + /// Returns an unmodifiable [Map] of the authentications, since none should be added + /// or deleted. + Map get authentications => Map.unmodifiable(_authentications); T getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } - // We don’t use a Map for queryParams. + // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, @@ -85,7 +84,7 @@ class ApiClient { } try { - // Special case for uploading a single file which isn’t a 'multipart/form-data'. + // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) @@ -115,7 +114,7 @@ class ApiClient { final msgBody = nullableContentType == 'application/x-www-form-urlencoded' ? formParams - : serialize(body); + : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { @@ -141,7 +140,44 @@ class ApiClient { throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); } - dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + Future deserializeAsync(String json, String targetType, {bool growable}) async => + // ignore: deprecated_member_use_from_same_package + deserialize(json, targetType, growable: growable); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') + dynamic deserialize(String json, String targetType, {bool growable}) { + // Remove all spaces. Necessary for regular expressions as well. + targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: growable == true); + } + + // ignore: deprecated_member_use_from_same_package + Future serializeAsync(Object value) async => serialize(value); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') + String serialize(Object value) => value == null ? '' : json.encode(value); + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { + authNames.forEach((authName) { + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } + auth.applyToParams(queryParams, headerParams); + }); + } + + static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { try { switch (targetType) { case 'String': @@ -172,56 +208,65 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) - .toList(growable: true == growable); + .map((v) => _deserialize(v, targetType, growable: growable)) + .toList(growable: growable); } if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) + .map((v) => _deserialize(v, targetType, growable: growable)) .toSet(); } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return Map.fromIterables( value.keys, - value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + value.values.map((v) => _deserialize(v, targetType, growable: growable)), ); } break; } - } on Exception catch (e, stack) { - throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', e, stack,); + } catch (error, trace) { + throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,); } throw ApiException(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',); } - - dynamic deserialize(String json, String targetType, {bool growable}) { - // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(' ', ''); - - return targetType == 'String' - ? json - : _deserialize(jsonDecode(json), targetType, growable: true == growable); - } - - String serialize(Object obj) => obj == null ? '' : json.encode(obj); - - /// Update query and header parameters based on authentication settings. - /// @param authNames The authentications to apply - void _updateParamsForAuth( - List authNames, - List queryParams, - Map headerParams, - ) { - authNames.forEach((authName) { - final auth = _authentications[authName]; - if (auth == null) { - throw ArgumentError('Authentication undefined: $authName'); - } - auth.applyToParams(queryParams, headerParams); - }); - } } + +/// Primarily intended for use in an isolate. +class DeserializationMessage { + const DeserializationMessage({ + @required this.json, + @required this.targetType, + this.growable, + }); + + /// The JSON value to deserialize. + final String json; + + /// Target type to deserialize to. + final String targetType; + + /// Whether to make deserialized lists or maps growable. + final bool growable; +} + +/// Primarily intended for use in an isolate. +Future deserializeAsync(DeserializationMessage message) async { + // Remove all spaces. Necessary for regular expressions as well. + final targetType = message.targetType.replaceAll(' ', ''); + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? message.json + : ApiClient._deserialize( + jsonDecode(message.json), + targetType, + growable: message.growable == true, + ); +} + +/// Primarily intended for use in an isolate. +Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart index 141f4a7f5b4..4135dcf95b2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart @@ -63,7 +63,7 @@ String parameterToString(dynamic value) { /// 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) { +Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart index d68dcf2e279..b0b0e5977da 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart @@ -15,7 +15,6 @@ import 'dart:io'; import 'package:http/http.dart'; import 'package:intl/intl.dart'; - import 'package:meta/meta.dart'; part 'api_client.dart'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart index 4dbc722ac17..c297f77a8a3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -78,13 +78,13 @@ class AnotherFakeApi { Future call123testSpecialTags(ModelClient modelClient) async { final response = await call123testSpecialTagsWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ModelClient') as ModelClient; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart index a75bdc33448..1185af2521c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart @@ -56,13 +56,13 @@ class DefaultApi { Future fooGet() async { final response = await fooGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'InlineResponseDefault') as InlineResponseDefault; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'InlineResponseDefault',) as InlineResponseDefault; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart index d25c1bcd4a5..20db8f0c9b0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart @@ -59,13 +59,13 @@ class FakeApi { Future fakeHealthGet() async { final response = await fakeHealthGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'HealthCheckResult') as HealthCheckResult; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'HealthCheckResult',) as HealthCheckResult; } return Future.value(null); } @@ -149,7 +149,7 @@ class FakeApi { Future fakeHttpSignatureTest(Pet pet, { String query1, String header1 }) async { final response = await fakeHttpSignatureTestWithHttpInfo(pet, query1: query1, header1: header1 ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -209,13 +209,13 @@ class FakeApi { Future fakeOuterBooleanSerialize({ bool body }) async { final response = await fakeOuterBooleanSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'bool') as bool; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'bool',) as bool; } return Future.value(null); } @@ -276,13 +276,13 @@ class FakeApi { Future fakeOuterCompositeSerialize({ OuterComposite outerComposite }) async { final response = await fakeOuterCompositeSerializeWithHttpInfo( outerComposite: outerComposite ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'OuterComposite') as OuterComposite; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'OuterComposite',) as OuterComposite; } return Future.value(null); } @@ -343,13 +343,13 @@ class FakeApi { Future fakeOuterNumberSerialize({ num body }) async { final response = await fakeOuterNumberSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'num') as num; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'num',) as num; } return Future.value(null); } @@ -410,13 +410,13 @@ class FakeApi { Future fakeOuterStringSerialize({ String body }) async { final response = await fakeOuterStringSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } return Future.value(null); } @@ -480,13 +480,13 @@ class FakeApi { Future fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty) async { final response = await fakePropertyEnumIntegerSerializeWithHttpInfo(outerObjectWithEnumProperty); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'OuterObjectWithEnumProperty') as OuterObjectWithEnumProperty; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'OuterObjectWithEnumProperty',) as OuterObjectWithEnumProperty; } return Future.value(null); } @@ -548,7 +548,7 @@ class FakeApi { Future testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) async { final response = await testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -613,7 +613,7 @@ class FakeApi { Future testBodyWithQueryParams(String query, User user) async { final response = await testBodyWithQueryParamsWithHttpInfo(query, user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -680,13 +680,13 @@ class FakeApi { Future testClientModel(ModelClient modelClient) async { final response = await testClientModelWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ModelClient') as ModelClient; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } return Future.value(null); } @@ -937,7 +937,7 @@ class FakeApi { Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, MultipartFile binary, DateTime date, DateTime dateTime, String password, String callback }) async { final response = await testEndpointParametersWithHttpInfo(number, double_, patternWithoutDelimiter, byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1077,7 +1077,7 @@ class FakeApi { Future testEnumParameters({ List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, int enumQueryInteger, double enumQueryDouble, List enumFormStringArray, String enumFormString }) async { final response = await testEnumParametersWithHttpInfo( enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1194,7 +1194,7 @@ class FakeApi { Future testGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int stringGroup, bool booleanGroup, int int64Group }) async { final response = await testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1257,7 +1257,7 @@ class FakeApi { Future testInlineAdditionalProperties(Map requestBody) async { final response = await testInlineAdditionalPropertiesWithHttpInfo(requestBody); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1343,7 +1343,7 @@ class FakeApi { Future testJsonFormData(String param, String param2) async { final response = await testJsonFormDataWithHttpInfo(param, param2); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1438,7 +1438,7 @@ class FakeApi { Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) async { final response = await testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index 0455f4c68f0..f7e337dbee5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -78,13 +78,13 @@ class FakeClassnameTags123Api { Future testClassname(ModelClient modelClient) async { final response = await testClassnameWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ModelClient') as ModelClient; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart index eacebcceace..af2215c4db7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart @@ -74,7 +74,7 @@ class PetApi { Future addPet(Pet pet) async { final response = await addPetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -146,7 +146,7 @@ class PetApi { Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -215,13 +215,13 @@ class PetApi { Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'List') as List) .cast() .toList(growable: false); } @@ -293,13 +293,13 @@ class PetApi { Future> findPetsByTags(Set tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return (apiClient.deserialize(_decodeBodyBytes(response), 'Set') as List) + return (await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Set') as List) .cast() .toSet(); } @@ -370,13 +370,13 @@ class PetApi { Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } return Future.value(null); } @@ -440,7 +440,7 @@ class PetApi { Future updatePet(Pet pet) async { final response = await updatePetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -530,7 +530,7 @@ class PetApi { Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -618,13 +618,13 @@ class PetApi { Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } return Future.value(null); } @@ -716,13 +716,13 @@ class PetApi { Future uploadFileWithRequiredFile(int petId, MultipartFile requiredFile, { String additionalMetadata }) async { final response = await uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata: additionalMetadata ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart index 91d115d44c8..ea459d16052 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart @@ -79,7 +79,7 @@ class StoreApi { Future deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -131,13 +131,13 @@ class StoreApi { Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); + return Map.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Map'),); } return Future>.value(null); } @@ -206,13 +206,13 @@ class StoreApi { Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(null); } @@ -276,13 +276,13 @@ class StoreApi { Future placeOrder(Order order) async { final response = await placeOrderWithHttpInfo(order); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } return Future.value(null); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart index 05ce7f9dec1..0a2c54c75fe 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart @@ -78,7 +78,7 @@ class UserApi { Future createUser(User user) async { final response = await createUserWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -141,7 +141,7 @@ class UserApi { Future createUsersWithArrayInput(List user) async { final response = await createUsersWithArrayInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -204,7 +204,7 @@ class UserApi { Future createUsersWithListInput(List user) async { final response = await createUsersWithListInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -272,7 +272,7 @@ class UserApi { Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -336,13 +336,13 @@ class UserApi { Future getUserByName(String username) async { final response = await getUserByNameWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'User',) as User; } return Future.value(null); } @@ -418,13 +418,13 @@ class UserApi { Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. if (response.body != null && response.statusCode != HttpStatus.noContent) { - return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; + return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } return Future.value(null); } @@ -473,7 +473,7 @@ class UserApi { Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -550,7 +550,7 @@ class UserApi { Future updateUser(String username, User user) async { final response = await updateUserWithHttpInfo(username, user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index 83da5a1e482..83cad2d3ded 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -47,17 +47,16 @@ class ApiClient { Map get defaultHeaderMap => _defaultHeaderMap; - /// returns an unmodifiable view of the authentications, since none should be added - /// nor deleted - Map get authentications => - Map.unmodifiable(_authentications); + /// Returns an unmodifiable [Map] of the authentications, since none should be added + /// or deleted. + Map get authentications => Map.unmodifiable(_authentications); T getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } - // We don’t use a Map for queryParams. + // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, @@ -88,7 +87,7 @@ class ApiClient { } try { - // Special case for uploading a single file which isn’t a 'multipart/form-data'. + // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) @@ -118,7 +117,7 @@ class ApiClient { final msgBody = nullableContentType == 'application/x-www-form-urlencoded' ? formParams - : serialize(body); + : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { @@ -144,7 +143,44 @@ class ApiClient { throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); } - dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + Future deserializeAsync(String json, String targetType, {bool growable}) async => + // ignore: deprecated_member_use_from_same_package + deserialize(json, targetType, growable: growable); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') + dynamic deserialize(String json, String targetType, {bool growable}) { + // Remove all spaces. Necessary for regular expressions as well. + targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? json + : _deserialize(jsonDecode(json), targetType, growable: growable == true); + } + + // ignore: deprecated_member_use_from_same_package + Future serializeAsync(Object value) async => serialize(value); + + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') + String serialize(Object value) => value == null ? '' : json.encode(value); + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void _updateParamsForAuth( + List authNames, + List queryParams, + Map headerParams, + ) { + authNames.forEach((authName) { + final auth = _authentications[authName]; + if (auth == null) { + throw ArgumentError('Authentication undefined: $authName'); + } + auth.applyToParams(queryParams, headerParams); + }); + } + + static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { try { switch (targetType) { case 'String': @@ -256,56 +292,65 @@ class ApiClient { default: Match match; if (value is List && (match = _regList.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) - .toList(growable: true == growable); + .map((v) => _deserialize(v, targetType, growable: growable)) + .toList(growable: growable); } if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return value - .map((v) => _deserialize(v, newTargetType, growable: growable)) + .map((v) => _deserialize(v, targetType, growable: growable)) .toSet(); } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - final newTargetType = match[1]; + targetType = match[1]; // ignore: parameter_assignments return Map.fromIterables( value.keys, - value.values.map((v) => _deserialize(v, newTargetType, growable: growable)), + value.values.map((v) => _deserialize(v, targetType, growable: growable)), ); } break; } - } on Exception catch (e, stack) { - throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', e, stack,); + } catch (error, trace) { + throw ApiException.withInner(HttpStatus.internalServerError, 'Exception during deserialization.', error, trace,); } throw ApiException(HttpStatus.internalServerError, 'Could not find a suitable class for deserialization',); } - - dynamic deserialize(String json, String targetType, {bool growable}) { - // Remove all spaces. Necessary for reg expressions as well. - targetType = targetType.replaceAll(' ', ''); - - return targetType == 'String' - ? json - : _deserialize(jsonDecode(json), targetType, growable: true == growable); - } - - String serialize(Object obj) => obj == null ? '' : json.encode(obj); - - /// Update query and header parameters based on authentication settings. - /// @param authNames The authentications to apply - void _updateParamsForAuth( - List authNames, - List queryParams, - Map headerParams, - ) { - authNames.forEach((authName) { - final auth = _authentications[authName]; - if (auth == null) { - throw ArgumentError('Authentication undefined: $authName'); - } - auth.applyToParams(queryParams, headerParams); - }); - } } + +/// Primarily intended for use in an isolate. +class DeserializationMessage { + const DeserializationMessage({ + @required this.json, + @required this.targetType, + this.growable, + }); + + /// The JSON value to deserialize. + final String json; + + /// Target type to deserialize to. + final String targetType; + + /// Whether to make deserialized lists or maps growable. + final bool growable; +} + +/// Primarily intended for use in an isolate. +Future deserializeAsync(DeserializationMessage message) async { + // Remove all spaces. Necessary for regular expressions as well. + final targetType = message.targetType.replaceAll(' ', ''); + + // If the expected target type is String, nothing to do... + return targetType == 'String' + ? message.json + : ApiClient._deserialize( + jsonDecode(message.json), + targetType, + growable: message.growable == true, + ); +} + +/// Primarily intended for use in an isolate. +Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart index ececff49c4c..96214037944 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart @@ -78,7 +78,7 @@ String parameterToString(dynamic value) { /// 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) { +Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api.dart index 9fdfdb55fb8..2803013466c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api.dart @@ -15,9 +15,8 @@ import 'dart:io'; import 'package:http/http.dart'; import 'package:intl/intl.dart'; - -import 'package:meta/meta.dart'; import 'package:json_annotation/json_annotation.dart'; +import 'package:meta/meta.dart'; part 'api_client.dart'; part 'api_helper.dart'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart index 29c7103abd3..b712431a035 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart @@ -78,7 +78,7 @@ class AnotherFakeApi { Future call123testSpecialTags(ModelClient modelClient) async { final response = await call123testSpecialTagsWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart index 6295891cd3c..779bdec8b3a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart @@ -56,7 +56,7 @@ class DefaultApi { Future fooGet() async { final response = await fooGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart index 21c888fa588..edcd08cfa4a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart @@ -59,7 +59,7 @@ class FakeApi { Future fakeHealthGet() async { final response = await fakeHealthGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -150,7 +150,7 @@ class FakeApi { Future fakeHttpSignatureTest(Pet pet, { String query1, String header1 }) async { final response = await fakeHttpSignatureTestWithHttpInfo(pet, query1: query1, header1: header1 ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -210,7 +210,7 @@ class FakeApi { Future fakeOuterBooleanSerialize({ bool body }) async { final response = await fakeOuterBooleanSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -278,7 +278,7 @@ class FakeApi { Future fakeOuterCompositeSerialize({ OuterComposite outerComposite }) async { final response = await fakeOuterCompositeSerializeWithHttpInfo( outerComposite: outerComposite ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -346,7 +346,7 @@ class FakeApi { Future fakeOuterNumberSerialize({ num body }) async { final response = await fakeOuterNumberSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -414,7 +414,7 @@ class FakeApi { Future fakeOuterStringSerialize({ String body }) async { final response = await fakeOuterStringSerializeWithHttpInfo( body: body ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -485,7 +485,7 @@ class FakeApi { Future fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty) async { final response = await fakePropertyEnumIntegerSerializeWithHttpInfo(outerObjectWithEnumProperty); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -554,7 +554,7 @@ class FakeApi { Future testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) async { final response = await testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -619,7 +619,7 @@ class FakeApi { Future testBodyWithQueryParams(String query, User user) async { final response = await testBodyWithQueryParamsWithHttpInfo(query, user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -686,7 +686,7 @@ class FakeApi { Future testClientModel(ModelClient modelClient) async { final response = await testClientModelWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -944,7 +944,7 @@ class FakeApi { Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, MultipartFile binary, DateTime date, DateTime dateTime, String password, String callback }) async { final response = await testEndpointParametersWithHttpInfo(number, double_, patternWithoutDelimiter, byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1084,7 +1084,7 @@ class FakeApi { Future testEnumParameters({ List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, int enumQueryInteger, double enumQueryDouble, List enumFormStringArray, String enumFormString }) async { final response = await testEnumParametersWithHttpInfo( enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1201,7 +1201,7 @@ class FakeApi { Future testGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int stringGroup, bool booleanGroup, int int64Group }) async { final response = await testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1264,7 +1264,7 @@ class FakeApi { Future testInlineAdditionalProperties(Map requestBody) async { final response = await testInlineAdditionalPropertiesWithHttpInfo(requestBody); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1350,7 +1350,7 @@ class FakeApi { Future testJsonFormData(String param, String param2) async { final response = await testJsonFormDataWithHttpInfo(param, param2); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -1445,7 +1445,7 @@ class FakeApi { Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) async { final response = await testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart index dc0b394f8fb..49f4ce7cde2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -78,7 +78,7 @@ class FakeClassnameTags123Api { Future testClassname(ModelClient modelClient) async { final response = await testClassnameWithHttpInfo(modelClient); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart index 6c43311b2e8..cd2a65ab939 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart @@ -74,7 +74,7 @@ class PetApi { Future addPet(Pet pet) async { final response = await addPetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -146,7 +146,7 @@ class PetApi { Future deletePet(int petId, { String apiKey }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -215,7 +215,7 @@ class PetApi { Future> findPetsByStatus(List status) async { final response = await findPetsByStatusWithHttpInfo(status); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -294,7 +294,7 @@ class PetApi { Future> findPetsByTags(Set tags) async { final response = await findPetsByTagsWithHttpInfo(tags); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -372,7 +372,7 @@ class PetApi { Future getPetById(int petId) async { final response = await getPetByIdWithHttpInfo(petId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -443,7 +443,7 @@ class PetApi { Future updatePet(Pet pet) async { final response = await updatePetWithHttpInfo(pet); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -533,7 +533,7 @@ class PetApi { Future updatePetWithForm(int petId, { String name, String status }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -621,7 +621,7 @@ class PetApi { Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -720,7 +720,7 @@ class PetApi { Future uploadFileWithRequiredFile(int petId, MultipartFile requiredFile, { String additionalMetadata }) async { final response = await uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata: additionalMetadata ); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart index dd5c2db3528..9e262c18b98 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart @@ -79,7 +79,7 @@ class StoreApi { Future deleteOrder(String orderId) async { final response = await deleteOrderWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -131,7 +131,7 @@ class StoreApi { Future> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -207,7 +207,7 @@ class StoreApi { Future getOrderById(int orderId) async { final response = await getOrderByIdWithHttpInfo(orderId); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -278,7 +278,7 @@ class StoreApi { Future placeOrder(Order order) async { final response = await placeOrderWithHttpInfo(order); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart index ba21021c9dd..3291afc2670 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart @@ -78,7 +78,7 @@ class UserApi { Future createUser(User user) async { final response = await createUserWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -141,7 +141,7 @@ class UserApi { Future createUsersWithArrayInput(List user) async { final response = await createUsersWithArrayInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -204,7 +204,7 @@ class UserApi { Future createUsersWithListInput(List user) async { final response = await createUsersWithListInputWithHttpInfo(user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -272,7 +272,7 @@ class UserApi { Future deleteUser(String username) async { final response = await deleteUserWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -336,7 +336,7 @@ class UserApi { Future getUserByName(String username) async { final response = await getUserByNameWithHttpInfo(username); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -419,7 +419,7 @@ class UserApi { Future loginUser(String username, String password) async { final response = await loginUserWithHttpInfo(username, password); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" @@ -475,7 +475,7 @@ class UserApi { Future logoutUser() async { final response = await logoutUserWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } @@ -552,7 +552,7 @@ class UserApi { Future updateUser(String username, User user) async { final response = await updateUserWithHttpInfo(username, user); if (response.statusCode >= HttpStatus.badRequest) { - throw ApiException(response.statusCode, _decodeBodyBytes(response)); + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart index 593d552210b..f54d8cad38d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart @@ -47,17 +47,16 @@ class ApiClient { Map get defaultHeaderMap => _defaultHeaderMap; - /// returns an unmodifiable view of the authentications, since none should be added - /// nor deleted - Map get authentications => - Map.unmodifiable(_authentications); + /// Returns an unmodifiable [Map] of the authentications, since none should be added + /// or deleted. + Map get authentications => Map.unmodifiable(_authentications); T getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } - // We don’t use a Map for queryParams. + // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( String path, @@ -88,7 +87,7 @@ class ApiClient { } try { - // Special case for uploading a single file which isn’t a 'multipart/form-data'. + // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) @@ -118,7 +117,7 @@ class ApiClient { final msgBody = nullableContentType == 'application/x-www-form-urlencoded' ? formParams - : serialize(body); + : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { @@ -144,8 +143,11 @@ class ApiClient { throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); } + // ignore: deprecated_member_use_from_same_package + Future serializeAsync(Object value) async => serialize(value); - String serialize(Object obj) => obj == null ? '' : json.encode(obj); + @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') + String serialize(Object value) => value == null ? '' : json.encode(value); /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply @@ -162,4 +164,8 @@ class ApiClient { auth.applyToParams(queryParams, headerParams); }); } + } + +/// Primarily intended for use in an isolate. +Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart index f9904f5ec71..51db433eb30 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart @@ -78,7 +78,7 @@ String parameterToString(dynamic value) { /// 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) { +Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes)