From 9a65a5f0db09a5d35f84737f2d20699051f12171 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Fri, 8 Jul 2016 15:02:28 +0200 Subject: [PATCH] feat: improve / fix deserialization by parsing type String * added api_helper.dart for a helper function. * defaultApiClient is now a variable instead of a static field inside ApiClient * a lot of functions inside ApiClient are no longer static. * optional params are now named params (needed to introduce a justIgnoreFlag as hack) * queryParams now support the multi format and are therefore no longer a Map, but a List * renamed apiException.mustache to api_exception.mustache to conform with other file names. * removed unused import: 'dart:html' * removed 'package:crypto/crypto.dart' dependency. 'dart:convert' has a base64 converter now. * use null-aware operator for apiClient assignment in xxxApi constructors. * enable testStoreApi (which returned a Future nobody waited for) * fix types in tests. Some ids were passed as Strings instead of ints. * adapt tests to use the optional named arguments (for optional query args) * generate random ids in tests. Otherwise insertion will always succeed if the test has been called once. --- .../codegen/languages/DartClientCodegen.java | 3 +- .../src/main/resources/dart/api.mustache | 24 +- .../main/resources/dart/api_client.mustache | 124 ++-- ...eption.mustache => api_exception.mustache} | 0 .../main/resources/dart/api_helper.mustache | 33 + .../src/main/resources/dart/apilib.mustache | 5 +- .../main/resources/dart/auth/oauth.mustache | 2 +- samples/client/petstore/dart/lib/api.dart | 6 +- .../client/petstore/dart/lib/api/pet_api.dart | 374 ++++++---- .../petstore/dart/lib/api/store_api.dart | 177 +++-- .../petstore/dart/lib/api/user_api.dart | 669 ++++++++++-------- .../client/petstore/dart/lib/api_client.dart | 160 +++-- .../client/petstore/dart/lib/api_helper.dart | 33 + .../petstore/dart/lib/auth/api_key_auth.dart | 5 +- .../dart/lib/auth/authentication.dart | 2 +- .../dart/lib/auth/http_basic_auth.dart | 4 +- .../client/petstore/dart/lib/auth/oauth.dart | 2 +- samples/client/petstore/dart/pubspec.lock | 213 ++++-- samples/client/petstore/dart/pubspec.yaml | 1 - .../client/petstore/dart/test/pet_test.dart | 78 +- .../client/petstore/dart/test/store_test.dart | 14 +- samples/client/petstore/dart/test/tests.dart | 9 +- .../client/petstore/dart/test/user_test.dart | 50 +- 23 files changed, 1193 insertions(+), 795 deletions(-) rename modules/swagger-codegen/src/main/resources/dart/{apiException.mustache => api_exception.mustache} (100%) create mode 100644 modules/swagger-codegen/src/main/resources/dart/api_helper.mustache create mode 100644 samples/client/petstore/dart/lib/api_helper.dart diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 6bb54cb9d50c..a70c5c4c692a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -141,7 +141,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); - supportingFiles.add(new SupportingFile("apiException.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index 6fcd49994ecf..04c24009380a 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -5,19 +5,19 @@ part of api; class {{classname}} { String basePath = "{{basePath}}"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - {{classname}}([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + {{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; {{#operation}} /// {{summary}} /// /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) async { + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} { {{#allParams}}{{^required}} {{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; // verify required params are set @@ -33,11 +33,13 @@ class {{classname}} { String path = "{{path}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{paramName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - {{#queryParams}}if("null" != {{paramName}}) - queryParams.addAll(convertParametersForCollectionFormat({{collectionFormat}}, {{baseName}}, {{paramName}})); + {{#queryParams}} + if("null" != {{paramName}}) { + queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + } {{/queryParams}} {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -84,7 +86,7 @@ class {{classname}} { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; + return {{#returnType}} apiClient.deserialize(response.body, '{{{returnType}}}') {{/returnType}}; } else { return {{#returnType}}null{{/returnType}}; } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 6a9fca0fd8e3..e83d8b62a6d8 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -7,46 +7,19 @@ class QueryParam { QueryParam(this.name, this.value); } -const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; - -// port from Java version -List convertParametersForCollectionFormat( - String collectionFormat, String name, dynamic value) { - var params = {}; - - // preconditions - if (name == null || name.isEmpty || value == null) return params; - - if (value is! List) { - params.add(new QueryParam(name, value as String)); - return params; - } - - List values = value as List; - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" - : collectionFormat; // default: csv - - if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, v)); - } - - String delimiter = _delimiters[collectionFormat] ?? ","; - - params.add(new QueryParam(name, values.join(delimiter))); - return params; -} - class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); + + var client = new {{#browserClient}}Browser{{/browserClient}}Client(); Map _defaultHeaderMap = {}; Map _authentications = {}; - static final dson = new Dartson.JSON(); + + final dson = new Dartson.JSON(); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + ApiClient() { // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} _authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} @@ -76,43 +49,57 @@ class ApiClient { } } - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - + dynamic _deserialize(dynamic value, String targetType) { try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + {{#models}} + {{#model}} + case '{{classname}}': + return dson.map(value, new {{classname}}()); + {{/model}} + {{/models}} + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var valueL = value as List; + var newTargetType = match[1]; + return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var valueM = value as Map; + var newTargetType = match[1]; + return new Map.fromIterables(valueM.keys, + valueM.values.map((v) => _deserialize(v, newTargetType))); + } + } } - } on FormatException { - // Just return the passed in value + } catch(e) { + // Just throw the ApiException below } - - return result; + throw new ApiException(500, 'Could not find a suitable class for deserialization'); } - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); - switch(clazz) { - {{#models}} - {{#model}} - case {{classname}}: - return isMap ? dson.map(json, new {{classname}}()) : dson.decode(json, new {{classname}}()); - {{/model}} - {{/models}} - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); } - static String serialize(Object obj) { + String serialize(Object obj) { String serialized = ''; if (obj == null) { serialized = ''; @@ -136,13 +123,9 @@ class ApiClient { String contentType, List authNames) async { - updateParamsForAuth(authNames, queryParams, headerParams); + _updateParamsForAuth(authNames, queryParams, headerParams); - var client = new {{#browserClient}}Browser{{/browserClient}}Client(); - - StringBuffer sb = new StringBuffer(); - - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.key}=${p.value}'); + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -177,12 +160,11 @@ class ApiClient { /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, List queryParams, Map headerParams) { + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); }); } - } diff --git a/modules/swagger-codegen/src/main/resources/dart/apiException.mustache b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/dart/apiException.mustache rename to modules/swagger-codegen/src/main/resources/dart/api_exception.mustache diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache new file mode 100644 index 000000000000..fb25306d2600 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -0,0 +1,33 @@ +part of api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +List _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, value as String)); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, v)); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 24b96817a03d..5d2f345703cd 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -2,13 +2,13 @@ library api; import 'dart:async'; import 'dart:convert';{{#browserClient}} -import 'dart:html'; import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -19,3 +19,6 @@ part 'auth/http_basic_auth.dart'; {{/apis}}{{/apiInfo}} {{#models}}{{#model}}part 'model/{{classFilename}}.dart'; {{/model}}{{/models}} + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache index 5e3e2c8b260d..e514dd85738a 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache @@ -3,7 +3,7 @@ part of api; class OAuth implements Authentication { @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/api.dart b/samples/client/petstore/dart/lib/api.dart index c296270af64f..1a0b0c84cc6b 100644 --- a/samples/client/petstore/dart/lib/api.dart +++ b/samples/client/petstore/dart/lib/api.dart @@ -2,14 +2,13 @@ library api; import 'dart:async'; import 'dart:convert'; -import 'dart:html'; import 'package:http/browser_client.dart'; import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; -import 'package:crypto/crypto.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -27,3 +26,6 @@ part 'model/pet.dart'; part 'model/tag.dart'; part 'model/user.dart'; + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/samples/client/petstore/dart/lib/api/pet_api.dart b/samples/client/petstore/dart/lib/api/pet_api.dart index b6c807e72f07..694ec340d464 100644 --- a/samples/client/petstore/dart/lib/api/pet_api.dart +++ b/samples/client/petstore/dart/lib/api/pet_api.dart @@ -1,34 +1,36 @@ part of api; + class PetApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - PetApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Add a new pet to the store /// /// - Future addPet(Pet body) { + Future addPet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/pet".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/json","application/xml"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -44,39 +46,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Deletes a pet /// /// - Future deletePet(int petId, String apiKey) { + Future deletePet(int petId, { String apiKey, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - headerParams["api_key"] = apiKey; + headerParams["api_key"] = apiKey; List contentTypes = []; @@ -93,37 +103,49 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Finds Pets by status /// /// Multiple status values can be provided with comma separated strings - Future> findPetsByStatus(List status) { + Future> findPetsByStatus(List status, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(status == null) { + throw new ApiException(400, "Missing required param: status"); } // create path and map variables String path = "/pet/findByStatus".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != status) - queryParams["status"] = status is List ? status.join(',') : status; + if("null" != status) { + queryParams.addAll(_convertParametersForCollectionFormat("csv", "status", status)); + } List contentTypes = []; @@ -140,37 +162,49 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') ; + } else { + return null; + } } /// Finds Pets by tags /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - Future> findPetsByTags(List tags) { + Future> findPetsByTags(List tags, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(tags == null) { + throw new ApiException(400, "Missing required param: tags"); } // create path and map variables String path = "/pet/findByTags".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != tags) - queryParams["tags"] = tags is List ? tags.join(',') : tags; + if("null" != tags) { + queryParams.addAll(_convertParametersForCollectionFormat("csv", "tags", tags)); + } List contentTypes = []; @@ -187,36 +221,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') ; + } else { + return null; + } } /// Find pet by ID /// /// Returns a single pet - Future getPetById(int petId) { + Future getPetById(int petId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -232,36 +277,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Pet') ; + } else { + return null; + } } /// Update an existing pet /// /// - Future updatePet(Pet body) { + Future updatePet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/pet".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/json","application/xml"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -277,42 +333,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Updates a pet in the store with form data /// /// - Future updatePetWithForm(int petId, String name, String status) { + Future updatePetWithForm(int petId, { String name, String status, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/x-www-form-urlencoded"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -342,42 +403,47 @@ if (status != null) formParams['status'] = apiClient.parameterToString(status); } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// uploads an image /// /// - Future uploadFile(int petId, String additionalMetadata, MultipartFile file) { + Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["multipart/form-data"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -407,16 +473,22 @@ if (status != null) } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, ApiResponse); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'ApiResponse') ; + } else { + return null; + } } } diff --git a/samples/client/petstore/dart/lib/api/store_api.dart b/samples/client/petstore/dart/lib/api/store_api.dart index 25e3ccfcf6e2..0e42d5346032 100644 --- a/samples/client/petstore/dart/lib/api/store_api.dart +++ b/samples/client/petstore/dart/lib/api/store_api.dart @@ -1,34 +1,36 @@ part of api; + class StoreApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - StoreApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Delete purchase order by ID /// /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - Future deleteOrder(String orderId) { + Future deleteOrder(String orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); } // create path and map variables String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -44,33 +46,44 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Returns pet inventories by status /// /// Returns a map of status codes to quantities - Future> getInventory() { + Future> getInventory( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set // create path and map variables String path = "/store/inventory".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -86,36 +99,47 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Map); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Map') ; + } else { + return null; + } } /// Find purchase order by ID /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - Future getOrderById(int orderId) { + Future getOrderById(int orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); } // create path and map variables String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -131,36 +155,47 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') ; + } else { + return null; + } } /// Place an order for a pet /// /// - Future placeOrder(Order body) { + Future placeOrder(Order body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/store/order".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -176,16 +211,22 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') ; + } else { + return null; + } } } diff --git a/samples/client/petstore/dart/lib/api/user_api.dart b/samples/client/petstore/dart/lib/api/user_api.dart index d774ea1f9313..34481806b955 100644 --- a/samples/client/petstore/dart/lib/api/user_api.dart +++ b/samples/client/petstore/dart/lib/api/user_api.dart @@ -1,265 +1,35 @@ part of api; + class UserApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - UserApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Create user /// /// This can only be done by the logged in user. - Future createUser(User body) { + Future createUser(User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/user".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Creates list of users with given input array - /// - /// - Future createUsersWithArrayInput(List body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/createWithArray".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Creates list of users with given input array - /// - /// - Future createUsersWithListInput(List body) { - Object postBody = body; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/createWithList".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Delete user - /// - /// This can only be done by the logged in user. - Future deleteUser(String username) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); - } - /// Get user by user name - /// - /// - Future getUserByName(String username) { - Object postBody = null; - // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - - List contentTypes = []; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - List authNames = []; - - if(contentType.startsWith("multipart/form-data")) { - bool hasFields = false; - MultipartRequest mp = new MultipartRequest(null, null); - - if(hasFields) - postBody = mp; - } - else { - } - - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, User); - } - else { - return null; - } - }); - } - /// Logs user into the system - /// - /// - Future loginUser(String username, String password) { - Object postBody = null; - // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - } - - // create path and map variables - String path = "/user/login".replaceAll("{format}","json"); - - // query params - Map queryParams = {}; - Map headerParams = {}; - Map formParams = {}; - if("null" != username) - queryParams["username"] = username is List ? username.join(',') : username; -if("null" != password) - queryParams["password"] = password is List ? password.join(',') : password; List contentTypes = []; @@ -276,33 +46,47 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, String); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } - /// Logs out current logged in user session + /// Creates list of users with given input array /// /// - Future logoutUser() { - Object postBody = null; + Future createUsersWithArrayInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } // create path and map variables - String path = "/user/logout".replaceAll("{format}","json"); + String path = "/user/createWithArray".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -318,39 +102,103 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } - /// Updated user + /// Creates list of users with given input array + /// + /// + Future createUsersWithListInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user/createWithList".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Delete user /// /// This can only be done by the logged in user. - Future updateUser(String username, User body) { - Object postBody = body; + Future deleteUser(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(username == null) { + throw new ApiException(400, "Missing required param: username"); } // create path and map variables String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -366,16 +214,255 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Get user by user name + /// + /// + Future getUserByName(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'User') ; + } else { + return null; + } + } + /// Logs user into the system + /// + /// + Future loginUser(String username, String password, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(password == null) { + throw new ApiException(400, "Missing required param: password"); + } + + // create path and map variables + String path = "/user/login".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + if("null" != username) { + queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); + } + if("null" != password) { + queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); + } + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'String') ; + } else { + return null; + } + } + /// Logs out current logged in user session + /// + /// + Future logoutUser( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = null; + + // verify required params are set + + // create path and map variables + String path = "/user/logout".replaceAll("{format}","json"); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } + } + /// Updated user + /// + /// This can only be done by the logged in user. + Future updateUser(String username, User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } + Object postBody = body; + + // verify required params are set + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(body == null) { + throw new ApiException(400, "Missing required param: body"); + } + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + List queryParams = []; + Map headerParams = {}; + Map formParams = {}; + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + } + + var response = await apiClient.invokeAPI(basePath, + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } } diff --git a/samples/client/petstore/dart/lib/api_client.dart b/samples/client/petstore/dart/lib/api_client.dart index c4e9a5b1d468..3014e7deadef 100644 --- a/samples/client/petstore/dart/lib/api_client.dart +++ b/samples/client/petstore/dart/lib/api_client.dart @@ -1,13 +1,25 @@ part of api; +class QueryParam { + String name; + String value; + + QueryParam(this.name, this.value); +} + class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); + + var client = new BrowserClient(); Map _defaultHeaderMap = {}; Map _authentications = {}; - static final dson = new Dartson.JSON(); + + final dson = new Dartson.JSON(); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + ApiClient() { // Setup authentications (key: authentication name, value: authentication). _authentications['petstore_auth'] = new OAuth(); @@ -36,49 +48,63 @@ class ApiClient { } } - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - + dynamic _deserialize(dynamic value, String targetType) { try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + case 'ApiResponse': + return dson.map(value, new ApiResponse()); + case 'Category': + return dson.map(value, new Category()); + case 'Order': + return dson.map(value, new Order()); + case 'Pet': + return dson.map(value, new Pet()); + case 'Tag': + return dson.map(value, new Tag()); + case 'User': + return dson.map(value, new User()); + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var valueL = value as List; + var newTargetType = match[1]; + return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var valueM = value as Map; + var newTargetType = match[1]; + return new Map.fromIterables(valueM.keys, + valueM.values.map((v) => _deserialize(v, newTargetType))); + } + } } - } on FormatException { - // Just return the passed in value + } catch(e) { + // Just throw the ApiException below } - - return result; + throw new ApiException(500, 'Could not find a suitable class for deserialization'); } - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); - switch(clazz) { - case ApiResponse: - return isMap ? dson.map(json, new ApiResponse()) : dson.decode(json, new ApiResponse()); - case Category: - return isMap ? dson.map(json, new Category()) : dson.decode(json, new Category()); - case Order: - return isMap ? dson.map(json, new Order()) : dson.decode(json, new Order()); - case Pet: - return isMap ? dson.map(json, new Pet()) : dson.decode(json, new Pet()); - case Tag: - return isMap ? dson.map(json, new Tag()) : dson.decode(json, new Tag()); - case User: - return isMap ? dson.map(json, new User()) : dson.decode(json, new User()); - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); } - static String serialize(Object obj) { + String serialize(Object obj) { String serialized = ''; if (obj == null) { serialized = ''; @@ -90,76 +116,60 @@ class ApiClient { return serialized; } - Future invokeAPI( String host, - String path, - String method, - Map queryParams, - Object body, - Map headerParams, - Map formParams, - String contentType, - List authNames) { + // We don't use a Map for queryParams. + // If collectionFormat is 'multi' a key might appear multiple times. + Future invokeAPI(String host, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) async { - updateParamsForAuth(authNames, queryParams, headerParams); + _updateParamsForAuth(authNames, queryParams, headerParams); - var client = new BrowserClient(); + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + String queryString = ps.isNotEmpty ? + '?' + ps.join('&') : + ''; - StringBuffer sb = new StringBuffer(); - - for(String key in queryParams.keys) { - String value = queryParams[key]; - if (value != null){ - if(sb.toString().length == 0) { - sb.write("?"); - } else { - sb.write("&"); - } - sb.write(key); - sb.write("="); - sb.write(value); - } - } - String querystring = sb.toString(); - - String url = host + path + querystring; + String url = host + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; - var completer = new Completer(); - if(body is MultipartRequest) { var request = new MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - client.send(request).then((response) => completer.complete(Response.fromStream(response))); + var response = await client.send(request); + return Response.fromStream(response); } else { var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); switch(method) { - case "GET": - return client.get(url, headers: headerParams); case "POST": return client.post(url, headers: headerParams, body: msgBody); case "PUT": return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + default: + return client.get(url, headers: headerParams); } } - - return completer.future; } /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); }); } - } diff --git a/samples/client/petstore/dart/lib/api_helper.dart b/samples/client/petstore/dart/lib/api_helper.dart new file mode 100644 index 000000000000..fb25306d2600 --- /dev/null +++ b/samples/client/petstore/dart/lib/api_helper.dart @@ -0,0 +1,33 @@ +part of api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +List _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, value as String)); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, v)); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/samples/client/petstore/dart/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/lib/auth/api_key_auth.dart index 6e728ae916ba..d80d6a6a213e 100644 --- a/samples/client/petstore/dart/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart/lib/auth/api_key_auth.dart @@ -10,7 +10,7 @@ class ApiKeyAuth implements Authentication { ApiKeyAuth(this.location, this.paramName); @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = '$apiKeyPrefix $apiKey'; @@ -19,10 +19,9 @@ class ApiKeyAuth implements Authentication { } if (location == 'query' && value != null) { - queryParams[paramName] = value; + queryParams.add(new QueryParam(paramName, value)); } else if (location == 'header' && value != null) { headerParams[paramName] = value; } } - } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/lib/auth/authentication.dart index 4833af90ec0d..c0b1f92a42d1 100644 --- a/samples/client/petstore/dart/lib/auth/authentication.dart +++ b/samples/client/petstore/dart/lib/auth/authentication.dart @@ -3,5 +3,5 @@ part of api; abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart index e681c25653db..0645d4358f53 100644 --- a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart @@ -6,9 +6,9 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str)); } } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/oauth.dart b/samples/client/petstore/dart/lib/auth/oauth.dart index 5e3e2c8b260d..e514dd85738a 100644 --- a/samples/client/petstore/dart/lib/auth/oauth.dart +++ b/samples/client/petstore/dart/lib/auth/oauth.dart @@ -3,7 +3,7 @@ part of api; class OAuth implements Authentication { @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } \ No newline at end of file diff --git a/samples/client/petstore/dart/pubspec.lock b/samples/client/petstore/dart/pubspec.lock index 1e4ba01779c3..b816620fa905 100644 --- a/samples/client/petstore/dart/pubspec.lock +++ b/samples/client/petstore/dart/pubspec.lock @@ -2,86 +2,177 @@ # See http://pub.dartlang.org/doc/glossary.html#lockfile packages: analyzer: - description: analyzer + description: + name: analyzer + url: "https://pub.dartlang.org" source: hosted - version: "0.25.0+1" + version: "0.26.4" args: - description: args + description: + name: args + url: "https://pub.dartlang.org" source: hosted - version: "0.13.2" + version: "0.13.4+2" + async: + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "1.11.0" barback: - description: barback + description: + name: barback + url: "https://pub.dartlang.org" source: hosted - version: "0.15.2+4" + version: "0.15.2+8" browser: - description: browser + description: + name: browser + url: "https://pub.dartlang.org" source: hosted version: "0.10.0+2" - collection: - description: collection - source: hosted - version: "1.1.1" - crypto: - description: crypto - source: hosted - version: "0.9.0" - dartson: - description: dartson - source: hosted - version: "0.2.4" - guinness: - description: guinness - source: hosted - version: "0.1.17" - http: - description: http - source: hosted - version: "0.11.2" - http_parser: - description: http_parser - source: hosted - version: "0.0.2+7" - intl: - description: intl - source: hosted - version: "0.12.4+2" - logging: - description: logging - source: hosted - version: "0.9.3" - path: - description: path - source: hosted - version: "1.3.6" - petitparser: - description: petitparser - source: hosted - version: "1.4.3" - pool: - description: pool + charcode: + description: + name: charcode + url: "https://pub.dartlang.org" source: hosted version: "1.1.0" + collection: + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.0" + csslib: + description: + name: csslib + url: "https://pub.dartlang.org" + source: hosted + version: "0.13.2" + dartson: + description: + name: dartson + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.5" + glob: + description: + name: glob + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.3" + guinness: + description: + name: guinness + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.18" + html: + description: + name: html + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.2+2" + http: + description: + name: http + url: "https://pub.dartlang.org" + source: hosted + version: "0.11.3+8" + http_parser: + description: + name: http_parser + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.2" + intl: + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.7+1" + logging: + description: + name: logging + url: "https://pub.dartlang.org" + source: hosted + version: "0.11.3" + package_config: + description: + name: package_config + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.5" + path: + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.9" + petitparser: + description: + name: petitparser + url: "https://pub.dartlang.org" + source: hosted + version: "1.5.3" + plugin: + description: + name: plugin + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0" + pool: + description: + name: pool + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.4" source_maps: - description: source_maps + description: + name: source_maps + url: "https://pub.dartlang.org" source: hosted - version: "0.10.1" + version: "0.10.1+1" source_span: - description: source_span + description: + name: source_span + url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "1.2.3" stack_trace: - description: stack_trace + description: + name: stack_trace + url: "https://pub.dartlang.org" source: hosted - version: "1.3.4" + version: "1.6.6" string_scanner: - description: string_scanner + description: + name: string_scanner + url: "https://pub.dartlang.org" source: hosted - version: "0.1.3+1" + version: "1.0.0" unittest: - description: unittest + description: + name: unittest + url: "https://pub.dartlang.org" source: hosted - version: "0.11.6+1" + version: "0.11.6+4" + utf: + description: + name: utf + url: "https://pub.dartlang.org" + source: hosted + version: "0.9.0+3" watcher: - description: watcher + description: + name: watcher + url: "https://pub.dartlang.org" source: hosted - version: "0.9.6" + version: "0.9.7+2" + yaml: + description: + name: yaml + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.10" +sdk: ">=1.14.0 <2.0.0" diff --git a/samples/client/petstore/dart/pubspec.yaml b/samples/client/petstore/dart/pubspec.yaml index cbc62b63ca1d..e74546ea2105 100644 --- a/samples/client/petstore/dart/pubspec.yaml +++ b/samples/client/petstore/dart/pubspec.yaml @@ -4,7 +4,6 @@ description: Swagger API client dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - crypto: "^0.9.0" intl: "^0.12.4+2" dev_dependencies: diff --git a/samples/client/petstore/dart/test/pet_test.dart b/samples/client/petstore/dart/test/pet_test.dart index f93c3ea3e373..e9a7ccd5fa75 100644 --- a/samples/client/petstore/dart/test/pet_test.dart +++ b/samples/client/petstore/dart/test/pet_test.dart @@ -5,7 +5,7 @@ testPetApi() { describe('Pet API ', () { it('adds a new pet and gets it by id', () async { - var id = 137; + var id = newId(); await petApi.addPet(new Pet()..id = id); var pet = await petApi.getPetById(id); @@ -13,45 +13,56 @@ testPetApi() { }); it('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(6789099)).toThrowWith(anInstanceOf: ApiException); + expect(petApi.getPetById(newId())) + .toThrowWith(anInstanceOf: ApiException); }); it('deletes existing pet by id', () async { - var id = 7689; + var id = newId(); await petApi.addPet(new Pet()..id = id); - await petApi.deletePet(id, 'special-key'); + await petApi.deletePet(id, apiKey: 'special-key'); expect(petApi.getPetById(id)).toThrowWith(anInstanceOf: ApiException); }); it('updates pet with form', () async { - var id = 52341; - await petApi.addPet(new Pet()..id = id..name='Snowy'); - await petApi.updatePetWithForm('$id', 'Doge', ''); + var id = newId(); + await petApi.addPet(new Pet() + ..id = id + ..name = 'Snowy'); + await petApi.updatePetWithForm(id, name: 'Doge', status: ''); var pet = await petApi.getPetById(id); expect(pet.name).toEqual('Doge'); }); it('updates existing pet', () async { - var id = 900001; + var id = newId(); var name = 'Snowy'; await petApi.addPet(new Pet()..id = id); - await petApi.updatePet(new Pet()..id = id..name = name); + await petApi.updatePet(new Pet() + ..id = id + ..name = name); var pet = await petApi.getPetById(id); expect(pet.name).toEqual(name); }); it('finds pets by status', () async { - var id1 = 754111; - var id2 = 1231341; - var id3 = 6776251; + var id1 = newId(); + var id2 = newId(); + var id3 = newId(); var status = 'available'; - return Future.wait([petApi.addPet(new Pet()..id = id1..status = status), - petApi.addPet(new Pet()..id = id2..status = status), - petApi.addPet(new Pet()..id = id3..status = 'sold')]) - .then((_) async { - + return Future.wait([ + petApi.addPet(new Pet() + ..id = id1 + ..status = status), + petApi.addPet(new Pet() + ..id = id2 + ..status = status), + petApi.addPet(new Pet() + ..id = id3 + ..status = 'sold') + ]).then((_) async { var pets = await petApi.findPetsByStatus([status]); var petIds = pets.map((pet) => pet.id).toList(); expect(petIds).toContain(id1); @@ -61,12 +72,26 @@ testPetApi() { }); it('finds pets by tag', () async { - var snowyId = 253156; - var grumpyId = 734215; - var snowyTags = [new Tag()..id=12211..name='terrier']; - var grumpyTags = [new Tag()..id=455803..name='grumpy']; - await petApi.addPet(new Pet()..id = snowyId..name = 'Snowy'..tags = snowyTags); - await petApi.addPet(new Pet()..id = grumpyId..name = 'Grumpy Cat'..tags = grumpyTags); + var snowyId = newId(); + var grumpyId = newId(); + var snowyTags = [ + new Tag() + ..id = newId() + ..name = 'terrier' + ]; + var grumpyTags = [ + new Tag() + ..id = newId() + ..name = 'grumpy' + ]; + await petApi.addPet(new Pet() + ..id = snowyId + ..name = 'Snowy' + ..tags = snowyTags); + await petApi.addPet(new Pet() + ..id = grumpyId + ..name = 'Grumpy Cat' + ..tags = grumpyTags); var pets = await petApi.findPetsByTags(['grumpy']); var petIds = pets.map((pet) => pet.id).toList(); @@ -75,11 +100,10 @@ testPetApi() { }); it('uploads a pet image', () async { - var id = 672322; + var id = newId(); await petApi.addPet(new Pet()..id = id); var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, '', file); + await petApi.uploadFile(id, additionalMetadata: '', file: file); }); - }); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/store_test.dart b/samples/client/petstore/dart/test/store_test.dart index 692760f1be10..39d9cecfac70 100644 --- a/samples/client/petstore/dart/test/store_test.dart +++ b/samples/client/petstore/dart/test/store_test.dart @@ -3,28 +3,26 @@ part of tests; testStoreApi() { var storeApi = new StoreApi(); - describe('Store API ', () async { - + describe('Store API ', () { it('places an order and gets it by id', () async { - var id = 4356; + var id = newId(); await storeApi.placeOrder(new Order()..id = id); - var order = await storeApi.getOrderById(id.toString()); + var order = await storeApi.getOrderById(id); expect(order.id).toEqual(id); }); it('deletes an order', () async { - var id = 637211; + var id = newId(); await storeApi.placeOrder(new Order()..id = id); await storeApi.deleteOrder(id.toString()); - expect(storeApi.getOrderById(id.toString())).toThrowWith(anInstanceOf: ApiException); + expect(storeApi.getOrderById(id)).toThrowWith(anInstanceOf: ApiException); }); it('gets the store inventory', () async { Map inventory = await storeApi.getInventory(); expect(inventory.length).not.toBe(0); }); - }); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/tests.dart b/samples/client/petstore/dart/test/tests.dart index 173a5587a4d8..9511ea17875d 100644 --- a/samples/client/petstore/dart/test/tests.dart +++ b/samples/client/petstore/dart/test/tests.dart @@ -1,6 +1,7 @@ library tests; import 'dart:async'; +import 'dart:math'; import 'package:http/http.dart'; import 'package:guinness/guinness.dart'; import 'package:swagger/api.dart'; @@ -9,8 +10,14 @@ part 'pet_test.dart'; part 'store_test.dart'; part 'user_test.dart'; +final random = new Random(); + +int newId() { + return random.nextInt(999999); +} + main() { testPetApi(); testStoreApi(); testUserApi(); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/user_test.dart b/samples/client/petstore/dart/test/user_test.dart index 886a6bc3c5d2..7188a1d25ea6 100644 --- a/samples/client/petstore/dart/test/user_test.dart +++ b/samples/client/petstore/dart/test/user_test.dart @@ -4,24 +4,31 @@ testUserApi() { var userApi = new UserApi(); describe('User API ', () { - it('creates a user', () async { - var id = 67567; + var id = newId(); var username = 'Mally45'; - await userApi.createUser(new User()..id = id..username = username); + await userApi.createUser(new User() + ..id = id + ..username = username); var user = await userApi.getUserByName(username); expect(user.id).toEqual(id); }); it('creates users with list input', () async { - var firstId = 46226; - var joe ='Joe'; + var firstId = newId(); + var joe = 'Joe'; var sally = 'Sally'; - var secondId = 95239; + var secondId = newId(); - var users = [ new User()..id = firstId..username = joe, - new User()..id = secondId..username = sally]; + var users = [ + new User() + ..id = firstId + ..username = joe, + new User() + ..id = secondId + ..username = sally + ]; await userApi.createUsersWithListInput(users); var firstUser = await userApi.getUserByName(joe); @@ -31,33 +38,40 @@ testUserApi() { }); it('updates a user', () async { - var username ='Arkjam89'; + var username = 'Arkjam89'; var email = 'test@example.com'; - var user = new User()..id = 733356..username = username; + var user = new User() + ..id = newId() + ..username = username; await userApi.createUser(user); user.email = email; - await userApi.updateUser(username,user); + await userApi.updateUser(username, user); var foundUser = await userApi.getUserByName(username); expect(foundUser.email).toEqual(email); }); it('deletes a user', () async { - var username ='Riddlem325'; - await userApi.createUser(new User()..id = 1231114..username = username); + var username = 'Riddlem325'; + await userApi.createUser(new User() + ..id = newId() + ..username = username); await userApi.deleteUser(username); - expect(userApi.getUserByName(username)).toThrowWith(anInstanceOf: ApiException); + expect(userApi.getUserByName(username)) + .toThrowWith(anInstanceOf: ApiException); }); it('logs a user in', () async { - var username ='sgarad625'; + var username = 'sgarad625'; var password = 'lokimoki1'; - var user = new User()..id = 733356..username = username..password = password; + var user = new User() + ..id = newId() + ..username = username + ..password = password; await userApi.createUser(user); var result = await userApi.loginUser(username, password); expect(result).toContain('logged in user session:'); }); - }); -} \ No newline at end of file +}