From 4f84c081b4d312a354ed4d3a9c5aea7c5ff43f05 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Mon, 1 Nov 2021 18:22:41 +0300 Subject: [PATCH 01/39] Fixed some issues --- CHANGELOG.md | 5 +- lib/src/code_generators/constants.dart | 2 + .../swagger_models_generator.dart | 66 ++++++++++++------- .../v2/swagger_models_generator_v2.dart | 5 -- .../v3/swagger_models_generator_v3.dart | 22 ------- pubspec.yaml | 2 +- 6 files changed, 50 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ed945fd..b218e5be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,7 @@ -# 2.2.1+1 +# 2.2.3 + +* Fixed Issue ([#138](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/138)) +* Fixed generation of fields with type int32, int64. Parsing it like int * Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/265)) * Fixed generation of responses and request bodies in separate file diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index ed35815f..8c219df9 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -38,6 +38,8 @@ const successDescriptions = ['Success', 'OK', 'default response']; const kBasicTypesMap = { 'integer': 'int', 'int': 'int', + 'int32': 'int', + 'int64': 'int', 'boolean': 'bool', 'bool': 'bool', 'string': 'String', diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index e976e40a..c1d4809c 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -18,7 +18,6 @@ abstract class SwaggerModelsGenerator { String generateRequestBodies( String dartCode, String fileName, GeneratorOptions options); - Map getModelProperties(Map modelMap); String getExtendsString(Map map); List getAllEnumNames(String swaggerFile); List getAllListEnumNames(String swaggerFile); @@ -309,6 +308,8 @@ abstract class SwaggerModelsGenerator { switch (parameter['type'] as String?) { case 'integer': case 'int': + case 'int32': + case 'int64': return 'int'; case 'boolean': return 'bool'; @@ -998,7 +999,7 @@ List ${neededName.camelCase}ListFromJson( List allEnumNames, List allEnumListNames, GeneratorOptions options) { - final properties = getModelProperties(map); + final properties = getModelProperties(map, schemas); var extendsString = options.useInheritance ? getExtendsString(map) : ''; @@ -1130,25 +1131,44 @@ int get hashCode => $allHashComponents; '''; } -} -// @override -// int get hashCode => -// runtimeType.hashCode ^ -// const DeepCollectionEquality().hash(itemId) ^ -// const DeepCollectionEquality().hash(resolution) ^ -// const DeepCollectionEquality().hash(watchlistItemType) ^ -// const DeepCollectionEquality().hash(sourceOrInstance) ^ -// const DeepCollectionEquality().hash(duration) ^ -// const DeepCollectionEquality().hash(bookmark) ^ -// const DeepCollectionEquality().hash(isAdult) ^ -// const DeepCollectionEquality().hash(ageRating) ^ -// const DeepCollectionEquality().hash(model) ^ -// const DeepCollectionEquality().hash(showId) ^ -// const DeepCollectionEquality().hash(brandingProviderId) ^ -// const DeepCollectionEquality().hash(seasonId) ^ -// const DeepCollectionEquality().hash(instanceId) ^ -// const DeepCollectionEquality().hash(mergedId) ^ -// const DeepCollectionEquality().hash(title) ^ -// const DeepCollectionEquality().hash(sources) ^ -// const DeepCollectionEquality().hash(isAboutThisSeriesAvailable); + Map getModelProperties( + Map modelMap, + Map schemas, + ) { + if (!modelMap.containsKey('allOf')) { + return modelMap['properties'] as Map? ?? {}; + } + + final allOf = modelMap['allOf'] as List; + + final newModelMap = allOf.firstWhere( + (m) => (m as Map).containsKey('properties'), + orElse: () => null, + ); + + if (newModelMap == null) { + return {}; + } + + final currentProperties = + newModelMap['properties'] as Map? ?? {}; + + final allOfRef = allOf.firstWhere( + (m) => (m as Map).containsKey('\$ref'), + orElse: () => null, + ); + + if (allOfRef != null) { + final refString = allOfRef['\$ref'].toString(); + final schema = schemas[refString.getUnformattedRef()]; + + final moreProperties = + schema['properties'] as Map? ?? {}; + + currentProperties.addAll(moreProperties); + } + + return currentProperties; + } +} diff --git a/lib/src/code_generators/v2/swagger_models_generator_v2.dart b/lib/src/code_generators/v2/swagger_models_generator_v2.dart index 3f20c8fd..a7c86310 100644 --- a/lib/src/code_generators/v2/swagger_models_generator_v2.dart +++ b/lib/src/code_generators/v2/swagger_models_generator_v2.dart @@ -106,11 +106,6 @@ class SwaggerModelsGeneratorV2 extends SwaggerModelsGenerator { return resultsWithPrefix; } - @override - Map getModelProperties(Map modelMap) { - return modelMap['properties'] as Map? ?? {}; - } - @override String getExtendsString(Map map) { return ''; diff --git a/lib/src/code_generators/v3/swagger_models_generator_v3.dart b/lib/src/code_generators/v3/swagger_models_generator_v3.dart index f7efa6b8..736c3713 100644 --- a/lib/src/code_generators/v3/swagger_models_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_models_generator_v3.dart @@ -287,28 +287,6 @@ class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { return resultsWithPrefix; } - @override - Map getModelProperties(Map modelMap) { - if (!modelMap.containsKey('allOf')) { - return modelMap['properties'] as Map? ?? {}; - } - - final allOf = modelMap['allOf'] as List; - - final newModelMap = allOf.firstWhere( - (m) => (m as Map).containsKey('properties'), - orElse: () => null, - ); - - if (newModelMap == null) { - return {}; - } - - final currentProperties = newModelMap['properties'] as Map; - - return currentProperties; - } - @override String getExtendsString(Map map) { if (map.containsKey('allOf')) { diff --git a/pubspec.yaml b/pubspec.yaml index 6955e772..5d474169 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.1+1 +version: 2.2.3 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 26c00bd94feec40699c366ef5425f695eef50b88 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Mon, 1 Nov 2021 18:29:55 +0300 Subject: [PATCH 02/39] Added fix for Field annotations. Updatec changelog and pubspec --- CHANGELOG.md | 1 + lib/src/code_generators/swagger_requests_generator.dart | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b218e5be..05f16b89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # 2.2.3 * Fixed Issue ([#138](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/138)) +* Fixed Issue ([#269](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/269)) * Fixed generation of fields with type int32, int64. Parsing it like int * Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/265)) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index e31b149c..5c1dc35e 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -281,7 +281,8 @@ class SwaggerRequestsGenerator { Expression _getParameterAnnotation(SwaggerRequestParameter parameter) { switch (parameter.inParameter) { case kFormData: - return refer(kField).call([]); + return refer(kField) + .call([literalString(parameter.name.replaceAll('\$', ''))]); case kBody: return refer(kBody.pascalCase).call([]); default: From 57186d56fe44e2e059677a11c9a78591e1feda2d Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 2 Nov 2021 18:53:48 +0300 Subject: [PATCH 03/39] Fixed lot of issues with AllOf support --- .../swagger_enums_generator.dart | 40 +++- .../swagger_models_generator.dart | 211 +++++++++++++++++- .../v2/swagger_models_generator_v2.dart | 52 ----- .../v3/swagger_models_generator_v3.dart | 146 ------------ .../generator_tests/enums_generator_test.dart | 1 + .../models_generator_test.dart | 6 + 6 files changed, 243 insertions(+), 213 deletions(-) diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index 357cbb21..d85fdce5 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -36,9 +36,10 @@ abstract class SwaggerEnumsGenerator { final enumsFromClasses = definitions.keys .map((String className) { return generateEnumsFromClasses( - SwaggerModelsGenerator.getValidatedClassName( - className.pascalCase), - definitions[className] as Map); + SwaggerModelsGenerator.getValidatedClassName(className.pascalCase), + definitions[className] as Map, + definitions, + ); }) .where((element) => element.isNotEmpty) .join('\n'); @@ -81,9 +82,10 @@ $enumsFromRequestBodies } return generateEnumsFromClasses( - SwaggerModelsGenerator.getValidatedClassName( - className.pascalCase), - schema as Map); + SwaggerModelsGenerator.getValidatedClassName(className.pascalCase), + schema as Map, + {}, + ); }) .where((element) => element.isNotEmpty) .join('\n'); @@ -110,9 +112,10 @@ $enumsFromRequestBodies } return generateEnumsFromClasses( - SwaggerModelsGenerator.getValidatedClassName( - className.pascalCase), - schema as Map); + SwaggerModelsGenerator.getValidatedClassName(className.pascalCase), + schema as Map, + {}, + ); }) .where((element) => element.isNotEmpty) .join('\n'); @@ -376,6 +379,7 @@ $enumMap String generateEnumsFromClasses( String className, Map map, + Map schemas, ) { if (map['enum'] != null) { return generateEnumContentIfPossible(map, className); @@ -400,6 +404,24 @@ $enumMap } else { properties = map['properties'] as Map? ?? {}; } + + var allOfRef = allOf.firstWhereOrNull( + (e) => (e as Map).containsKey('\$ref'), + ) as Map?; + + if (allOfRef != null) { + final ref = allOfRef['\$ref'] as String; + + final allOfModel = + schemas[ref.getUnformattedRef()] as Map? ?? {}; + + final allOfModelProperties = + allOfModel['properties'] as Map? ?? {}; + + properties.addAll(allOfModelProperties); + + final tt = 9; + } } else { properties = map['properties'] as Map? ?? {}; } diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index c1d4809c..c93f3a64 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1,6 +1,9 @@ import 'dart:convert'; +import 'package:collection/src/iterable_extensions.dart'; import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/v3/swagger_enums_generator_v3.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/code_generators/v2/swagger_enums_generator_v2.dart'; @@ -19,10 +22,10 @@ abstract class SwaggerModelsGenerator { String generateRequestBodies( String dartCode, String fileName, GeneratorOptions options); String getExtendsString(Map map); - List getAllEnumNames(String swaggerFile); List getAllListEnumNames(String swaggerFile); String generateModelClassContent( + String swaggerFile, String className, Map map, Map schemas, @@ -50,6 +53,7 @@ abstract class SwaggerModelsGenerator { } return generateModelClassString( + swaggerFile, className, map, schemas, @@ -149,6 +153,26 @@ abstract class SwaggerModelsGenerator { return results; } + static Map getClassesFromSchemasResponses( + String dartCode, GeneratorOptions options) { + final swagger = jsonDecode(dartCode); + + final results = {}; + + final components = swagger['components'] as Map?; + if (components == null) { + return results; + } + + final responses = components['responses'] as Map?; + + if (responses == null) { + return results; + } + + return responses; + } + String generateBase( String dartCode, String fileName, @@ -181,6 +205,7 @@ abstract class SwaggerModelsGenerator { } return generateModelClassContent( + dartCode, className.pascalCase, classes[className] as Map, classes, @@ -792,6 +817,7 @@ abstract class SwaggerModelsGenerator { } String generatePropertiesContent( + String swagger, Map propertiesMap, Map schemas, String className, @@ -813,7 +839,7 @@ abstract class SwaggerModelsGenerator { propertiesMap[propertyName] as Map; final propertyKey = propertyName; - final basicTypesMap = generateBasicTypesMapFromSchemas(schemas); + final basicTypesMap = generateBasicTypesMapFromSchemas(swagger); propertyName = propertyName.asParameterName(); @@ -863,11 +889,21 @@ abstract class SwaggerModelsGenerator { } static Map generateBasicTypesMapFromSchemas( - Map schemas) { + String swaggerFile) { final result = {}; - if (schemas.isEmpty) { - return result; - } + + final swagger = jsonDecode(swaggerFile); + + final components = swagger['components'] as Map? ?? {}; + + final definitions = swagger['definitions'] as Map? ?? {}; + + final schemas = components['schemas'] as Map? ?? {}; + + final responses = components['responses'] as Map? ?? {}; + + schemas.addAll(definitions); + schemas.addAll(responses); schemas.forEach((key, value) { if (kBasicTypes.contains(value['type'].toString().toLowerCase()) && @@ -991,6 +1027,7 @@ List ${neededName.camelCase}ListFromJson( } String generateModelClassString( + String swaggerFile, String className, Map map, Map schemas, @@ -1013,6 +1050,7 @@ List ${neededName.camelCase}ListFromJson( ); final generatedProperties = generatePropertiesContent( + swaggerFile, properties, schemas, className, @@ -1171,4 +1209,165 @@ $allHashComponents; return currentProperties; } + + List getAllEnumNames(String swaggerFile) { + final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); + + final swagger = jsonDecode(swaggerFile); + + final components = swagger['components'] as Map?; + + final definitions = swagger['definitions'] as Map? ?? {}; + + final schemas = components == null + ? {} + : components['schemas'] as Map? ?? {}; + + schemas.addAll(definitions); + + final responses = components == null + ? null + : components['responses'] as Map?; + + final requestBodies = components == null + ? null + : components['requestBodies'] as Map?; + + schemas.forEach((className, map) { + final mapMap = map as Map; + if (mapMap.containsKey('enum')) { + results.add( + SwaggerModelsGenerator.getValidatedClassName(className.capitalize)); + return; + } + + if (mapMap['type'] == 'array' && + mapMap['items'] != null && + mapMap['items']['enum'] != null) { + results.add( + SwaggerModelsGenerator.getValidatedClassName(className.capitalize)); + return; + } + + Map? properties; + + if (mapMap.containsKey('allOf')) { + final allOf = mapMap['allOf'] as List; + var propertiesContainer = allOf.firstWhereOrNull( + (e) => (e as Map).containsKey('properties')) + as Map?; + + if (propertiesContainer != null) { + properties = + propertiesContainer['properties'] as Map? ?? {}; + } else { + properties = map['properties'] as Map? ?? {}; + } + + var allOfRef = allOf.firstWhereOrNull( + (e) => (e as Map).containsKey('\$ref'), + ) as Map?; + + if (allOfRef != null) { + final ref = allOfRef['\$ref'] as String; + + final allOfModel = + schemas[ref.getUnformattedRef()] as Map? ?? {}; + + final allOfModelProperties = + allOfModel['properties'] as Map? ?? {}; + + properties.addAll(allOfModelProperties); + } + } else { + properties = map['properties'] as Map?; + } + + if (properties == null) { + return; + } + + properties.forEach((propertyName, propertyValue) { + var property = propertyValue as Map; + + if (property.containsKey('enum') || + (property['items'] != null && property['items']['enum'] != null)) { + results.add(SwaggerModelsGenerator.getValidatedClassName( + SwaggerEnumsGeneratorV3().generateEnumName( + SwaggerModelsGenerator.getValidatedClassName(className), + propertyName))); + } + }); + }); + + if (responses != null) { + responses.forEach((className, map) { + final response = responses[className]; + final content = response['content'] as Map?; + final firstContent = content?.entries.firstOrNull?.value; + final schema = firstContent == null ? null : firstContent['schema']; + if (schema != null && + (schema as Map).containsKey('enum')) { + results.add(className.capitalize); + return; + } + final properties = schema == null + ? null + : schema['properties'] as Map?; + + if (properties == null) { + return; + } + + properties.forEach((propertyName, propertyValue) { + var property = propertyValue as Map; + + if (property.containsKey('enum') || + (property['items'] != null && + property['items']['enum'] != null)) { + results.add(SwaggerEnumsGeneratorV3() + .generateEnumName(className, propertyName)); + } + }); + }); + } + + if (requestBodies != null) { + requestBodies.forEach((className, map) { + final response = requestBodies[className]; + final content = response['content'] as Map; + final firstContent = content.entries.firstOrNull?.value; + final schema = firstContent == null ? null : firstContent['schema']; + if (schema != null && + (schema as Map).containsKey('enum')) { + results.add(className.capitalize); + return; + } + final properties = schema == null + ? null + : schema['properties'] as Map?; + + if (properties == null) { + return; + } + + properties.forEach((propertyName, propertyValue) { + var property = propertyValue as Map; + + if (property.containsKey('enum') || + (property['items'] != null && + property['items']['enum'] != null)) { + results.add(SwaggerEnumsGeneratorV3() + .generateEnumName(className, propertyName)); + } + }); + }); + } + + final resultsWithPrefix = results.map((element) { + return 'enums.$element'; + }).toList(); + + return resultsWithPrefix; + } } diff --git a/lib/src/code_generators/v2/swagger_models_generator_v2.dart b/lib/src/code_generators/v2/swagger_models_generator_v2.dart index a7c86310..798b1641 100644 --- a/lib/src/code_generators/v2/swagger_models_generator_v2.dart +++ b/lib/src/code_generators/v2/swagger_models_generator_v2.dart @@ -25,58 +25,6 @@ class SwaggerModelsGeneratorV2 extends SwaggerModelsGenerator { return ''; } - @override - List getAllEnumNames(String swaggerFile) { - final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); - - final swagger = jsonDecode(swaggerFile); - - final definitions = swagger['definitions'] as Map? ?? {}; - - if (definitions.isNotEmpty) { - definitions.forEach((className, map) { - final mapMap = map as Map; - if (mapMap.containsKey('enum')) { - results.add(SwaggerModelsGenerator.getValidatedClassName( - className.capitalize)); - return; - } - - if (mapMap['type'] == 'array' && - mapMap['items'] != null && - mapMap['items']['enum'] != null) { - results.add(SwaggerModelsGenerator.getValidatedClassName( - className.capitalize)); - return; - } - - final properties = map['properties'] as Map?; - - if (properties == null) { - return; - } - - properties.forEach((propertyName, propertyValue) { - var property = propertyValue as Map; - - if (property.containsKey('enum') || - (property['items'] != null && - property['items']['enum'] != null)) { - results.add(SwaggerEnumsGeneratorV2().generateEnumName( - SwaggerModelsGenerator.getValidatedClassName(className), - propertyName)); - } - }); - }); - } - - final resultsWithPrefix = results.map((element) { - return 'enums.$element'; - }).toList(); - - return resultsWithPrefix; - } - @override List getAllListEnumNames(String swaggerFile) { final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); diff --git a/lib/src/code_generators/v3/swagger_models_generator_v3.dart b/lib/src/code_generators/v3/swagger_models_generator_v3.dart index 736c3713..cea04b63 100644 --- a/lib/src/code_generators/v3/swagger_models_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_models_generator_v3.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; -import 'package:swagger_dart_code_generator/src/code_generators/v3/swagger_enums_generator_v3.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:collection/collection.dart'; @@ -109,151 +108,6 @@ class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { return generateBase(dartCode, fileName, options, result, false); } - @override - List getAllEnumNames(String swaggerFile) { - final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); - - final swagger = jsonDecode(swaggerFile); - - final components = swagger['components'] as Map?; - - final schemas = components == null - ? null - : components['schemas'] as Map?; - - final responses = components == null - ? null - : components['responses'] as Map?; - - final requestBodies = components == null - ? null - : components['requestBodies'] as Map?; - - if (schemas != null) { - schemas.forEach((className, map) { - final mapMap = map as Map; - if (mapMap.containsKey('enum')) { - results.add(SwaggerModelsGenerator.getValidatedClassName( - className.capitalize)); - return; - } - - if (mapMap['type'] == 'array' && - mapMap['items'] != null && - mapMap['items']['enum'] != null) { - results.add(SwaggerModelsGenerator.getValidatedClassName( - className.capitalize)); - return; - } - - Map? properties; - - if (mapMap.containsKey('allOf')) { - final allOf = mapMap['allOf'] as List; - var propertiesContainer = allOf.firstWhereOrNull( - (e) => (e as Map).containsKey('properties')) - as Map?; - - if (propertiesContainer != null) { - properties = - propertiesContainer['properties'] as Map?; - } else { - properties = map['properties'] as Map?; - } - } else { - properties = map['properties'] as Map?; - } - - if (properties == null) { - return; - } - - properties.forEach((propertyName, propertyValue) { - var property = propertyValue as Map; - - if (property.containsKey('enum') || - (property['items'] != null && - property['items']['enum'] != null)) { - results.add(SwaggerModelsGenerator.getValidatedClassName( - SwaggerEnumsGeneratorV3().generateEnumName( - SwaggerModelsGenerator.getValidatedClassName(className), - propertyName))); - } - }); - }); - } - - if (responses != null) { - responses.forEach((className, map) { - final response = responses[className]; - final content = response['content'] as Map?; - final firstContent = content?.entries.firstOrNull?.value; - final schema = firstContent == null ? null : firstContent['schema']; - if (schema != null && - (schema as Map).containsKey('enum')) { - results.add(className.capitalize); - return; - } - final properties = schema == null - ? null - : schema['properties'] as Map?; - - if (properties == null) { - return; - } - - properties.forEach((propertyName, propertyValue) { - var property = propertyValue as Map; - - if (property.containsKey('enum') || - (property['items'] != null && - property['items']['enum'] != null)) { - results.add(SwaggerEnumsGeneratorV3() - .generateEnumName(className, propertyName)); - } - }); - }); - } - - if (requestBodies != null) { - requestBodies.forEach((className, map) { - final response = requestBodies[className]; - final content = response['content'] as Map; - final firstContent = content.entries.firstOrNull?.value; - final schema = firstContent == null ? null : firstContent['schema']; - if (schema != null && - (schema as Map).containsKey('enum')) { - results.add(className.capitalize); - return; - } - final properties = schema == null - ? null - : schema['properties'] as Map?; - - if (properties == null) { - return; - } - - properties.forEach((propertyName, propertyValue) { - var property = propertyValue as Map; - - if (property.containsKey('enum') || - (property['items'] != null && - property['items']['enum'] != null)) { - results.add(SwaggerEnumsGeneratorV3() - .generateEnumName(className, propertyName)); - } - }); - }); - } - - final resultsWithPrefix = results.map((element) { - return 'enums.$element'; - }).toList(); - - return resultsWithPrefix; - } - @override List getAllListEnumNames(String swaggerFile) { final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); diff --git a/test/generator_tests/enums_generator_test.dart b/test/generator_tests/enums_generator_test.dart index 66ddd171..77bb701f 100644 --- a/test/generator_tests/enums_generator_test.dart +++ b/test/generator_tests/enums_generator_test.dart @@ -24,6 +24,7 @@ void main() { test('Should generate enum from request parameter', () { final result = generator.generate(request_with_enum_in_parameter, 'test_file'); + expect(result, contains('enum V3OrderOrderIdStatePutOrderStateRequest')); }); diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 31955062..9b7d3c50 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -323,6 +323,7 @@ void main() { const factoryConstructorExpectedResult = '\tfactory Animals.fromJson(Map json) => _\$AnimalsFromJson(json);\n'; final result = generator.generateModelClassContent( + '', className, map, {}, @@ -344,6 +345,7 @@ void main() { const factoryConstructorExpectedResult = '\tfactory Animals.fromJson(Map json) => _\$AnimalsFromJson(json);\n'; final result = generator2.generateModelClassContent( + '', className, map, {}, @@ -448,6 +450,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( + '', map, {}, className, @@ -472,6 +475,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( + '', map, {}, className, @@ -494,6 +498,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( + '', map, {}, className, @@ -516,6 +521,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: '\$with')\n"; const fieldExpectedResult = 'final Pet? \$with'; final result = generator.generatePropertiesContent( + '', map, {}, className, From 9c20696cdd509d63d2d55791f025e29f16e3c316 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 2 Nov 2021 18:55:29 +0300 Subject: [PATCH 04/39] Updated changelog and pubspec --- CHANGELOG.md | 5 +++++ pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05f16b89..74ce5372 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.2.4 + +* Fixes issues with allOf support +* Fixed issue with basic types in responses models + # 2.2.3 * Fixed Issue ([#138](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/138)) diff --git a/pubspec.yaml b/pubspec.yaml index 5d474169..57c35b12 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.3 +version: 2.2.4 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 0a5e0a1216dba34503af8caa885be4b45d4b6e8f Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Thu, 4 Nov 2021 18:50:12 +0300 Subject: [PATCH 05/39] Added requestbodies generation from requests --- example/build.yaml | 2 +- lib/src/code_generators/constants.dart | 1 + .../swagger_requests_generator.dart | 5 ++ .../v3/swagger_models_generator_v3.dart | 60 ++++++++++++++++++- 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/example/build.yaml b/example/build.yaml index 32c917d5..3b4b2699 100644 --- a/example/build.yaml +++ b/example/build.yaml @@ -20,7 +20,7 @@ targets: use_path_for_request_names: true use_default_null_for_lists: false build_only_models: false - separate_models: true + separate_models: false enums_case_sensitive: false ignore_headers: false use_required_attribute_for_headers: false diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 8c219df9..19fdc55a 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -18,6 +18,7 @@ const kBasicTypes = [ const kChopperService = 'ChopperService'; const kChopperApi = 'ChopperApi'; const kResponse = 'Response'; +const kRequestBody = 'RequestBody'; const kFutureResponse = 'Future'; const kString = 'string'; const kUndefinedParameter = 'undefinedParameter'; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 5c1dc35e..59b2625d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -463,6 +463,7 @@ class SwaggerRequestsGenerator { schema: schema, modelPostfix: options.modelPostfix, root: root, + requestPath: path + requestType.pascalCase, ); } } @@ -525,6 +526,7 @@ class SwaggerRequestsGenerator { required SwaggerSchema schema, required String modelPostfix, required SwaggerRoot root, + required String requestPath, }) { if (schema.type.isNotEmpty) { if (schema.type == kArray) { @@ -545,6 +547,9 @@ class SwaggerRequestsGenerator { } return ''; + } else if (schema.type == kObject) { + return SwaggerModelsGenerator.getValidatedClassName( + '$requestPath\$$kRequestBody'); } return kBasicTypesMap[schema.type] ?? schema.type; diff --git a/lib/src/code_generators/v3/swagger_models_generator_v3.dart b/lib/src/code_generators/v3/swagger_models_generator_v3.dart index cea04b63..cc2527f0 100644 --- a/lib/src/code_generators/v3/swagger_models_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_models_generator_v3.dart @@ -1,9 +1,12 @@ import 'dart:convert'; +import 'package:recase/recase.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:collection/collection.dart'; +import 'package:swagger_dart_code_generator/src/swagger_models/swagger_root.dart'; class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { @override @@ -63,6 +66,54 @@ class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { return generateBase(dartCode, fileName, options, result, false); } + Map _getRequestBodiesFromRequests(String dartCode) { + final root = jsonDecode(dartCode) as Map; + + final paths = root['paths'] as Map?; + + if (paths == null) { + return {}; + } + + final result = {}; + + paths.forEach((pathKey, pathValue) { + final requests = pathValue as Map; + + requests.forEach((requestKey, requestValue) { + if (!supportedRequestTypes.contains(requestKey)) { + return; + } + + final requestBody = + requestValue['requestBody'] as Map?; + + if (requestBody != null) { + final content = requestBody['content'] as Map?; + if (content != null) { + final appJson = content.values.first as Map?; + if (appJson != null) { + final schema = appJson['schema'] as Map?; + + if (schema != null) { + if (schema['type'] == 'object' && + schema.containsKey('properties')) { + final className = + '${pathKey.pascalCase}${requestKey.pascalCase}\$$kRequestBody'; + + result[SwaggerModelsGenerator.getValidatedClassName( + className)] = requestBody; + } + } + } + } + } + }); + }); + + return result; + } + @override String generateRequestBodies( String dartCode, String fileName, GeneratorOptions options) { @@ -70,10 +121,13 @@ class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { final components = map['components'] as Map?; final requestBodies = components == null - ? null - : components['requestBodies'] as Map?; + ? {} + : components['requestBodies'] as Map? ?? + {}; + + requestBodies.addAll(_getRequestBodiesFromRequests(dartCode)); - if (requestBodies == null) { + if (requestBodies.isEmpty) { return ''; } From e22cf427dd64d8ca329e7b191a67967f30830cb1 Mon Sep 17 00:00:00 2001 From: Elliana May Date: Wed, 10 Nov 2021 15:41:56 +0800 Subject: [PATCH 06/39] Add windows support (#273) * Run CI on windows too * chore: Fix a number of path joins * fix: Revert change to getFileNameWithoutExtension * fix: Normalize paths used for extensions --- .github/workflows/master.yml | 7 ++++- lib/src/extensions/file_name_extensions.dart | 9 ++---- lib/swagger_dart_code_generator.dart | 33 ++++++++++++-------- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 285925b0..d7fb1a77 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -7,7 +7,12 @@ on: jobs: build: - runs-on: ubuntu-latest + runs-on: ${{ matrix.runs-on }} + + strategy: + matrix: + runs-on: [windows-latest, ubuntu-latest] + steps: - uses: actions/checkout@v2.1.0 - uses: subosito/flutter-action@v1 diff --git a/lib/src/extensions/file_name_extensions.dart b/lib/src/extensions/file_name_extensions.dart index 6b78f241..6751e81a 100644 --- a/lib/src/extensions/file_name_extensions.dart +++ b/lib/src/extensions/file_name_extensions.dart @@ -1,7 +1,8 @@ import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; +import 'package:path/path.dart' as p; String getClassNameFromFileName(String file) { - final name = file.split('.').first.replaceAll('-', '_'); + final name = getFileNameWithoutExtension(file).replaceAll('-', '_'); final result = name.split('_').map((String e) => e.capitalize); return result.join(); } @@ -11,9 +12,5 @@ String getFileNameWithoutExtension(String file) { } String getFileNameBase(String filePath) { - final fileName = filePath.split('/').last.replaceAll('-', '_'); - - final lastDot = fileName.lastIndexOf('.'); - - return fileName.substring(0, lastDot); + return p.basenameWithoutExtension(filePath).replaceAll('-', '_'); } diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 38c638a9..9ed49e96 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -4,6 +4,7 @@ import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:swagger_dart_code_generator/src/swagger_code_generator.dart'; import 'package:universal_io/io.dart'; import 'package:dart_style/dart_style.dart'; +import 'package:path/path.dart' show join, normalize; ///Returns instance of SwaggerDartCodeGenerator SwaggerDartCodeGenerator swaggerCodeBuilder(BuilderOptions options) => @@ -18,26 +19,32 @@ const String _outputResponsesFileExtension = '.responses.swagger.dart'; const String _indexFileName = 'client_index.dart'; const String _mappingFileName = 'client_mapping.dart'; +String normal(String path) { + return AssetId('', path).path; +} + Map> _generateExtensions(GeneratorOptions options) { - final filesList = Directory(options.inputFolder).listSync().where( + final filesList = Directory(normalize(options.inputFolder)).listSync().where( (FileSystemEntity file) => _inputFileExtensions.any((ending) => file.path.endsWith(ending))); final result = >{}; + var out = normalize(options.outputFolder); + filesList.forEach((FileSystemEntity element) { final name = getFileNameBase(element.path); - result[element.path] = [ - '${options.outputFolder}$name$_outputFileExtension', - '${options.outputFolder}$name$_outputEnumsFileExtension', - '${options.outputFolder}$name$_outputModelsFileExtension', - '${options.outputFolder}$name$_outputResponsesFileExtension', + result[normal(element.path)] = [ + join(out, '$name$_outputFileExtension'), + join(out, '$name$_outputEnumsFileExtension'), + join(out, '$name$_outputModelsFileExtension'), + join(out, '$name$_outputResponsesFileExtension'), ]; }); ///Register additional outputs in first input - result[filesList.first.path]!.add('${options.outputFolder}$_indexFileName'); - result[filesList.first.path]!.add('${options.outputFolder}$_mappingFileName'); + result[normal(filesList.first.path)]!.add(join(out, _indexFileName)); + result[normal(filesList.first.path)]!.add(join(out, _mappingFileName)); return result; } @@ -104,7 +111,7 @@ class SwaggerDartCodeGenerator implements Builder { final dateToJson = codeGenerator.generateDateToJson(contents); final copyAssetId = AssetId(buildStep.inputId.package, - '${options.outputFolder}$fileNameWithoutExtension$_outputFileExtension'); + join(options.outputFolder, '$fileNameWithoutExtension$_outputFileExtension')); if (!options.separateModels || !options.buildOnlyModels) { await buildStep.writeAsString( @@ -125,7 +132,7 @@ class SwaggerDartCodeGenerator implements Builder { final formatterEnums = _tryFormatCode(enums); final enumsAssetId = AssetId(buildStep.inputId.package, - '${options.outputFolder}$fileNameWithoutExtension$_outputEnumsFileExtension'); + join(options.outputFolder, '$fileNameWithoutExtension$_outputEnumsFileExtension')); await buildStep.writeAsString(enumsAssetId, formatterEnums); } @@ -141,7 +148,7 @@ class SwaggerDartCodeGenerator implements Builder { )); final enumsAssetId = AssetId(buildStep.inputId.package, - '${options.outputFolder}$fileNameWithoutExtension$_outputModelsFileExtension'); + join(options.outputFolder, '$fileNameWithoutExtension$_outputModelsFileExtension')); await buildStep.writeAsString(enumsAssetId, formattedModels); } @@ -200,7 +207,7 @@ $dateToJson final codeGenerator = SwaggerCodeGenerator(); final indexAssetId = - AssetId(inputId.package, '${options.outputFolder}$_indexFileName'); + AssetId(inputId.package, join(options.outputFolder, _indexFileName)); final imports = codeGenerator.generateIndexes(swaggerCode, buildExtensions); @@ -210,7 +217,7 @@ $dateToJson if (options.withConverter && !options.buildOnlyModels) { final mappingAssetId = - AssetId(inputId.package, '${options.outputFolder}$_mappingFileName'); + AssetId(inputId.package, join(options.outputFolder, _mappingFileName)); final mapping = codeGenerator.generateConverterMappings( swaggerCode, buildExtensions, hasModels); From 73d60e22dc2fc1ab8c827c736d45e8210bd839b0 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 10:56:47 +0300 Subject: [PATCH 07/39] Fixed errors with requestBodies generation --- .../swagger_models_generator.dart | 58 +++++++++++++++++-- .../v3/swagger_enums_generator_v3.dart | 21 +++++-- 2 files changed, 70 insertions(+), 9 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index c93f3a64..822c5eb2 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1213,7 +1213,7 @@ $allHashComponents; List getAllEnumNames(String swaggerFile) { final results = SwaggerEnumsGenerator.getEnumNamesFromRequests(swaggerFile); - final swagger = jsonDecode(swaggerFile); + final swagger = jsonDecode(swaggerFile) as Map; final components = swagger['components'] as Map?; @@ -1230,8 +1230,12 @@ $allHashComponents; : components['responses'] as Map?; final requestBodies = components == null - ? null - : components['requestBodies'] as Map?; + ? {} + : components['requestBodies'] as Map? ?? {}; + + final moreRequestBodies = getRequestBodiesFromRequests(swagger); + + requestBodies.addAll(moreRequestBodies); schemas.forEach((className, map) { final mapMap = map as Map; @@ -1332,7 +1336,7 @@ $allHashComponents; }); } - if (requestBodies != null) { + if (requestBodies.isNotEmpty) { requestBodies.forEach((className, map) { final response = requestBodies[className]; final content = response['content'] as Map; @@ -1370,4 +1374,50 @@ $allHashComponents; return resultsWithPrefix; } + + static Map getRequestBodiesFromRequests( + Map map) { + final paths = map['paths'] as Map? ?? {}; + if (paths.isEmpty) { + return {}; + } + + final result = {}; + + paths.forEach((pathKey, pathValue) { + final pathMap = pathValue as Map; + + pathMap.forEach((requestKey, requestValue) { + if (!supportedRequestTypes.contains(requestKey)) { + return; + } + + final requestMap = requestValue as Map? ?? {}; + + if (requestMap.containsKey('requestBody')) { + final requestBody = requestMap['requestBody'] as Map; + final content = requestBody['content'] as Map?; + if (content != null) { + final appJson = content.values.first as Map?; + if (appJson != null) { + final schema = appJson['schema'] as Map?; + + if (schema != null) { + if (schema['type'] == 'object' && + schema.containsKey('properties')) { + final className = + '${pathKey.pascalCase}${requestKey.pascalCase}\$$kRequestBody'; + + result[SwaggerModelsGenerator.getValidatedClassName( + className)] = requestBody; + } + } + } + } + } + }); + }); + + return result; + } } diff --git a/lib/src/code_generators/v3/swagger_enums_generator_v3.dart b/lib/src/code_generators/v3/swagger_enums_generator_v3.dart index f4abe81c..e75fdb55 100644 --- a/lib/src/code_generators/v3/swagger_enums_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_enums_generator_v3.dart @@ -1,10 +1,13 @@ import 'dart:convert'; +import 'package:recase/recase.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; class SwaggerEnumsGeneratorV3 extends SwaggerEnumsGenerator { @override String generate(String dartCode, String fileName) { - final dynamic map = jsonDecode(dartCode); + final map = jsonDecode(dartCode) as Map; final components = map['components'] as Map?; final schemas = components == null @@ -16,10 +19,18 @@ class SwaggerEnumsGeneratorV3 extends SwaggerEnumsGenerator { : components['responses'] as Map?; final requestBodies = components == null - ? null - : components['requestBodies'] as Map?; + ? {} + : components['requestBodies'] as Map? ?? {}; + + requestBodies + .addAll(SwaggerModelsGenerator.getRequestBodiesFromRequests(map)); - return generateFromMap(dartCode, fileName, schemas ?? {}, responses ?? {}, - requestBodies ?? {}); + return generateFromMap( + dartCode, + fileName, + schemas ?? {}, + responses ?? {}, + requestBodies, + ); } } From cfc205fd440548dcd88751a5e70309ca8b363e83 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 11:06:28 +0300 Subject: [PATCH 08/39] Added possibility to use operationId for request name --- .../code_generators/swagger_requests_generator.dart | 10 +++++++++- lib/src/models/generator_options.dart | 4 ++++ lib/src/models/generator_options.g2.dart | 3 +++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 59b2625d..06004b7c 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -591,7 +591,15 @@ class SwaggerRequestsGenerator { required String path, required String requestType, }) { - return SwaggerModelsGenerator.generateRequestName(path, requestType); + String methodName; + if (options.usePathForRequestNames || swaggerRequest.operationId.isEmpty) { + methodName = + SwaggerModelsGenerator.generateRequestName(path, requestType); + } else { + methodName = swaggerRequest.operationId; + } + + return methodName; } static SwaggerResponse? getSuccessedResponse({ diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 34658621..1074d046 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -19,6 +19,7 @@ class GeneratorOptions { required this.outputFolder, this.enumsCaseSensitive = true, this.useRequiredAttributeForHeaders = true, + this.usePathForRequestNames = true, this.useInheritance = true, this.includeIfNull, this.modelPostfix = '', @@ -30,6 +31,9 @@ class GeneratorOptions { factory GeneratorOptions.fromJson(Map json) => _$GeneratorOptionsFromJson(json); + @JsonKey(defaultValue: true) + final bool usePathForRequestNames; + @JsonKey(defaultValue: true) final bool withBaseUrl; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 7468b417..6f4c6033 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -36,6 +36,8 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( enumsCaseSensitive: json['enums_case_sensitive'] as bool? ?? false, useRequiredAttributeForHeaders: json['use_required_attribute_for_headers'] as bool? ?? true, + usePathForRequestNames: + json['use_path_for_request_names'] as bool? ?? true, useInheritance: json['use_inheritance'] as bool? ?? true, includeIfNull: json['include_if_null'] as bool?, modelPostfix: json['model_postfix'] as String? ?? '', @@ -51,6 +53,7 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( Map _$GeneratorOptionsToJson(GeneratorOptions instance) => { + 'use_path_for_request_names': instance.usePathForRequestNames, 'with_base_url': instance.withBaseUrl, 'with_converter': instance.withConverter, 'separate_models': instance.separateModels, From 364a7b4e234906d24c844851aa25736fc0db08b0 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 11:06:53 +0300 Subject: [PATCH 09/39] Format code --- lib/swagger_dart_code_generator.dart | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 9ed49e96..898c2ab4 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -110,8 +110,10 @@ class SwaggerDartCodeGenerator implements Builder { final dateToJson = codeGenerator.generateDateToJson(contents); - final copyAssetId = AssetId(buildStep.inputId.package, - join(options.outputFolder, '$fileNameWithoutExtension$_outputFileExtension')); + final copyAssetId = AssetId( + buildStep.inputId.package, + join(options.outputFolder, + '$fileNameWithoutExtension$_outputFileExtension')); if (!options.separateModels || !options.buildOnlyModels) { await buildStep.writeAsString( @@ -131,8 +133,10 @@ class SwaggerDartCodeGenerator implements Builder { ///Write enums final formatterEnums = _tryFormatCode(enums); - final enumsAssetId = AssetId(buildStep.inputId.package, - join(options.outputFolder, '$fileNameWithoutExtension$_outputEnumsFileExtension')); + final enumsAssetId = AssetId( + buildStep.inputId.package, + join(options.outputFolder, + '$fileNameWithoutExtension$_outputEnumsFileExtension')); await buildStep.writeAsString(enumsAssetId, formatterEnums); } @@ -147,8 +151,10 @@ class SwaggerDartCodeGenerator implements Builder { enums.isNotEmpty, )); - final enumsAssetId = AssetId(buildStep.inputId.package, - join(options.outputFolder, '$fileNameWithoutExtension$_outputModelsFileExtension')); + final enumsAssetId = AssetId( + buildStep.inputId.package, + join(options.outputFolder, + '$fileNameWithoutExtension$_outputModelsFileExtension')); await buildStep.writeAsString(enumsAssetId, formattedModels); } @@ -216,8 +222,8 @@ $dateToJson } if (options.withConverter && !options.buildOnlyModels) { - final mappingAssetId = - AssetId(inputId.package, join(options.outputFolder, _mappingFileName)); + final mappingAssetId = AssetId( + inputId.package, join(options.outputFolder, _mappingFileName)); final mapping = codeGenerator.generateConverterMappings( swaggerCode, buildExtensions, hasModels); From 42ee7ed0f0cdfca4235b8714cb9b77d934f53a19 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 11:11:20 +0300 Subject: [PATCH 10/39] Updated pubspec and changelog --- CHANGELOG.md | 7 +++++++ pubspec.yaml | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74ce5372..2571e22e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# 2.2.5 + +* Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/265)) +* Fixed Issue ([#275](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/275)) +* Returned possibility to use operationId for request name +* Added generation of requestBodies integrated to requests, when it's complex model + # 2.2.4 * Fixes issues with allOf support diff --git a/pubspec.yaml b/pubspec.yaml index 57c35b12..c8c5cf87 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.4 +version: 2.2.5 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 2da139318db36ef98d1e6a6cfa9652be7a99f0b0 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 11:17:24 +0300 Subject: [PATCH 11/39] Fix tests --- test/generator_tests/models_generator_test.dart | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 9b7d3c50..100b4bcb 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -4,6 +4,7 @@ import 'package:swagger_dart_code_generator/src/code_generators/v3/swagger_model import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:test/test.dart'; import '../code_examples.dart'; +import 'test_data.dart'; void main() { final generator = SwaggerModelsGeneratorV3(); @@ -450,7 +451,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( - '', + carsService, map, {}, className, @@ -475,7 +476,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( - '', + carsService, map, {}, className, @@ -498,7 +499,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: 'animals')\n"; const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( - '', + carsService, map, {}, className, @@ -521,7 +522,7 @@ void main() { const jsonKeyExpectedResult = "\t@JsonKey(name: '\$with')\n"; const fieldExpectedResult = 'final Pet? \$with'; final result = generator.generatePropertiesContent( - '', + carsService, map, {}, className, From 95c44786eb197f1020a85b1239670d2821ac3c12 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 11:21:58 +0300 Subject: [PATCH 12/39] Fix analyser issues --- lib/src/code_generators/swagger_enums_generator.dart | 2 -- lib/src/code_generators/v2/swagger_models_generator_v2.dart | 1 - lib/src/code_generators/v3/swagger_enums_generator_v3.dart | 2 -- lib/src/code_generators/v3/swagger_models_generator_v3.dart | 1 - 4 files changed, 6 deletions(-) diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index d85fdce5..6c65ece9 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -419,8 +419,6 @@ $enumMap allOfModel['properties'] as Map? ?? {}; properties.addAll(allOfModelProperties); - - final tt = 9; } } else { properties = map['properties'] as Map? ?? {}; diff --git a/lib/src/code_generators/v2/swagger_models_generator_v2.dart b/lib/src/code_generators/v2/swagger_models_generator_v2.dart index 798b1641..22b5f4c9 100644 --- a/lib/src/code_generators/v2/swagger_models_generator_v2.dart +++ b/lib/src/code_generators/v2/swagger_models_generator_v2.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; -import 'package:swagger_dart_code_generator/src/code_generators/v2/swagger_enums_generator_v2.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; diff --git a/lib/src/code_generators/v3/swagger_enums_generator_v3.dart b/lib/src/code_generators/v3/swagger_enums_generator_v3.dart index e75fdb55..849a247b 100644 --- a/lib/src/code_generators/v3/swagger_enums_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_enums_generator_v3.dart @@ -1,6 +1,4 @@ import 'dart:convert'; -import 'package:recase/recase.dart'; -import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; diff --git a/lib/src/code_generators/v3/swagger_models_generator_v3.dart b/lib/src/code_generators/v3/swagger_models_generator_v3.dart index cc2527f0..5f1413e3 100644 --- a/lib/src/code_generators/v3/swagger_models_generator_v3.dart +++ b/lib/src/code_generators/v3/swagger_models_generator_v3.dart @@ -6,7 +6,6 @@ import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_g import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:collection/collection.dart'; -import 'package:swagger_dart_code_generator/src/swagger_models/swagger_root.dart'; class SwaggerModelsGeneratorV3 extends SwaggerModelsGenerator { @override From bdd025bcb71d0eeb30b31aa4676ea7c6158f2078 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 12 Nov 2021 14:23:59 +0300 Subject: [PATCH 13/39] Updated example readme --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2571e22e..956b1b77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.2.5+1 + +* Updated example + # 2.2.5 * Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/265)) diff --git a/pubspec.yaml b/pubspec.yaml index c8c5cf87..6e9b97fe 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.5 +version: 2.2.5+1 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From e5de95ae0ef260e13787991f111ce4f894f69f9c Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 19 Nov 2021 15:34:21 +0300 Subject: [PATCH 14/39] Removed converter generator --- analysis_options.yaml | 2 - example/build.yaml | 2 +- example/lib/example_swagger.swagger | 113 -- example/lib/main.dart | 11 + example/lib/pets_api.json | 1036 +++++++++++++++++ .../swagger_generated_code/client_index.dart | 2 +- .../client_mapping.dart | 6 +- .../example_swagger.swagger.chopper2.dart | 33 - .../example_swagger.swagger.dart | 256 ---- .../example_swagger.swagger.g2.dart | 66 -- lib/src/code_generators/constants.dart | 3 + .../swagger_additions_generator.dart | 30 +- .../swagger_converter_generator.dart | 86 -- .../swagger_requests_generator.dart | 92 +- lib/src/definitions.dart | 1 - lib/src/extensions/string_extension.dart | 2 + lib/src/swagger_code_generator.dart | 5 - lib/swagger_dart_code_generator.dart | 7 - .../converter_generator_test.dart | 47 - 19 files changed, 1135 insertions(+), 665 deletions(-) delete mode 100644 example/lib/example_swagger.swagger create mode 100644 example/lib/main.dart create mode 100644 example/lib/pets_api.json delete mode 100644 example/lib/swagger_generated_code/example_swagger.swagger.chopper2.dart delete mode 100644 example/lib/swagger_generated_code/example_swagger.swagger.dart delete mode 100644 example/lib/swagger_generated_code/example_swagger.swagger.g2.dart delete mode 100644 lib/src/definitions.dart delete mode 100644 test/generator_tests/converter_generator_test.dart diff --git a/analysis_options.yaml b/analysis_options.yaml index b429b96c..53f872bd 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -6,8 +6,6 @@ analyzer: strong-mode: implicit-casts: false exclude: - - example/**/*.dart - - lib/**/*.g2.dart linter: rules: - type_annotate_public_apis diff --git a/example/build.yaml b/example/build.yaml index 3b4b2699..62c21ecd 100644 --- a/example/build.yaml +++ b/example/build.yaml @@ -15,7 +15,7 @@ targets: input_folder: "lib/" output_folder: "lib/swagger_generated_code/" use_inheritance: false - with_base_url: false + with_base_url: true with_converter: true use_path_for_request_names: true use_default_null_for_lists: false diff --git a/example/lib/example_swagger.swagger b/example/lib/example_swagger.swagger deleted file mode 100644 index e47a0b40..00000000 --- a/example/lib/example_swagger.swagger +++ /dev/null @@ -1,113 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "Generated API", - "version": "1.0" - }, - "tags": [ - { - "name": "tag1" - }, - { - "name": "tag2" - } - ], - "paths": { - "/rooms": { - "get": { - "operationId": "getRooms", - "parameters": [ - { - "type": "string", - "description": "Rooms owner", - "name": "id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "Loaded rooms", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/room" - } - } - } - } - } - }, - "/api/item/all": { - "get": { - "tags": [ - "tag1" - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListCustomItem" - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "room": { - "type": "object", - "properties": { - "author": { - "description": "UUIDv4 of author of last message", - "type": "string" - }, - "avatar": { - "description": "UUIDv4 of fake user as avatar of room", - "type": "string" - }, - "id": { - "description": "UUIDv4 of room", - "type": "string" - }, - "lastMessage": { - "description": "Last message payload", - "type": "string" - }, - "name": { - "description": "Fake user name as room name", - "type": "string" - } - } - }, - "CustomItem": { - "type": "object", - "properties": { - "available": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "ListCustomItem": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CustomItem" - } - } - } - } -} \ No newline at end of file diff --git a/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 00000000..b21f6d03 --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,11 @@ +import 'package:example/swagger_generated_code/client_index.dart'; +import 'package:example/swagger_generated_code/pets_api.swagger.dart'; + +void main() async { + final api = PetsApi.create(); + + final items = + await api.petFindByStatusGet(status: PetFindByStatusGetStatus.available); + + print(items); +} diff --git a/example/lib/pets_api.json b/example/lib/pets_api.json new file mode 100644 index 00000000..ca1a8f69 --- /dev/null +++ b/example/lib/pets_api.json @@ -0,0 +1,1036 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "tags": [ + { + "name": "pet", + "description": "Everything about your Pets", + "externalDocs": { + "description": "Find out more", + "url": "http://swagger.io" + } + }, + { + "name": "store", + "description": "Access to Petstore orders" + }, + { + "name": "user", + "description": "Operations about user", + "externalDocs": { + "description": "Find out more about our store", + "url": "http://swagger.io" + } + } + ], + "schemes": [ + "https", + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma separated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": true, + "type": "array", + "items": { + "type": "string", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ], + "deprecated": true + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 10, + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "integer", + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be updated", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Pet": { + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } +} \ No newline at end of file diff --git a/example/lib/swagger_generated_code/client_index.dart b/example/lib/swagger_generated_code/client_index.dart index 08d3fe96..a12ba42e 100644 --- a/example/lib/swagger_generated_code/client_index.dart +++ b/example/lib/swagger_generated_code/client_index.dart @@ -1 +1 @@ -export 'example_swagger.swagger.dart' show ExampleSwagger; +export 'pets_api.swagger.dart' show PetsApi; diff --git a/example/lib/swagger_generated_code/client_mapping.dart b/example/lib/swagger_generated_code/client_mapping.dart index efc9ccdb..1b4bf0d8 100644 --- a/example/lib/swagger_generated_code/client_mapping.dart +++ b/example/lib/swagger_generated_code/client_mapping.dart @@ -1,5 +1 @@ -import 'example_swagger.swagger.dart'; - -final Map)> generatedMapping = { - ...ExampleSwaggerJsonDecoderMappings, -}; +final Map)> generatedMapping = {}; diff --git a/example/lib/swagger_generated_code/example_swagger.swagger.chopper2.dart b/example/lib/swagger_generated_code/example_swagger.swagger.chopper2.dart deleted file mode 100644 index ed1578b4..00000000 --- a/example/lib/swagger_generated_code/example_swagger.swagger.chopper2.dart +++ /dev/null @@ -1,33 +0,0 @@ -//Generated code - -part of 'example_swagger.swagger.dart'; - -// ************************************************************************** -// ChopperGenerator -// ************************************************************************** - -// ignore_for_file: always_put_control_body_on_new_line, always_specify_types, prefer_const_declarations -class _$ExampleSwagger extends ExampleSwagger { - _$ExampleSwagger([ChopperClient? client]) { - if (client == null) return; - this.client = client; - } - - @override - final definitionType = ExampleSwagger; - - @override - Future>> roomsGet({required String? id}) { - final $url = '/rooms'; - final $params = {'id': id}; - final $request = Request('GET', $url, client.baseUrl, parameters: $params); - return client.send, Room>($request); - } - - @override - Future> apiItemAllGet() { - final $url = '/api/item/all'; - final $request = Request('GET', $url, client.baseUrl); - return client.send($request); - } -} diff --git a/example/lib/swagger_generated_code/example_swagger.swagger.dart b/example/lib/swagger_generated_code/example_swagger.swagger.dart deleted file mode 100644 index dc5a923e..00000000 --- a/example/lib/swagger_generated_code/example_swagger.swagger.dart +++ /dev/null @@ -1,256 +0,0 @@ -import 'package:json_annotation/json_annotation.dart'; -import 'package:collection/collection.dart'; - -import 'package:chopper/chopper.dart'; -import 'package:chopper/chopper.dart' as chopper; - -part 'example_swagger.swagger.chopper2.dart'; -part 'example_swagger.swagger.g2.dart'; - -// ************************************************************************** -// SwaggerChopperGenerator -// ************************************************************************** - -@ChopperApi() -abstract class ExampleSwagger extends ChopperService { - static ExampleSwagger create([ChopperClient? client]) { - if (client != null) { - return _$ExampleSwagger(client); - } - - final newClient = ChopperClient( - services: [_$ExampleSwagger()], - converter: $JsonSerializableConverter(), - /*baseUrl: YOUR_BASE_URL*/ - ); - return _$ExampleSwagger(newClient); - } - - /// - ///@param id Rooms owner - @Get(path: '/rooms') - Future>> roomsGet( - {@Query('id') required String? id}); - - /// - @Get(path: '/api/item/all') - Future> apiItemAllGet(); -} - -final Map)> - ExampleSwaggerJsonDecoderMappings = { - Room: Room.fromJsonFactory, - CustomItem: CustomItem.fromJsonFactory, - ListCustomItem: ListCustomItem.fromJsonFactory, -}; - -@JsonSerializable(explicitToJson: true) -class Room { - Room({ - this.author, - this.avatar, - this.id, - this.lastMessage, - this.name, - }); - - factory Room.fromJson(Map json) => _$RoomFromJson(json); - - @JsonKey(name: 'author', includeIfNull: false, defaultValue: '') - final String? author; - @JsonKey(name: 'avatar', includeIfNull: false, defaultValue: '') - final String? avatar; - @JsonKey(name: 'id', includeIfNull: false, defaultValue: '') - final String? id; - @JsonKey(name: 'lastMessage', includeIfNull: false, defaultValue: '') - final String? lastMessage; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$RoomFromJson; - static const toJsonFactory = _$RoomToJson; - Map toJson() => _$RoomToJson(this); - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Room && - (identical(other.author, author) || - const DeepCollectionEquality().equals(other.author, author)) && - (identical(other.avatar, avatar) || - const DeepCollectionEquality().equals(other.avatar, avatar)) && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.lastMessage, lastMessage) || - const DeepCollectionEquality() - .equals(other.lastMessage, lastMessage)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - int get hashCode => - const DeepCollectionEquality().hash(author) ^ - const DeepCollectionEquality().hash(avatar) ^ - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(lastMessage) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $RoomExtension on Room { - Room copyWith( - {String? author, - String? avatar, - String? id, - String? lastMessage, - String? name}) { - return Room( - author: author ?? this.author, - avatar: avatar ?? this.avatar, - id: id ?? this.id, - lastMessage: lastMessage ?? this.lastMessage, - name: name ?? this.name); - } -} - -@JsonSerializable(explicitToJson: true) -class CustomItem { - CustomItem({ - this.available, - this.description, - this.id, - this.name, - }); - - factory CustomItem.fromJson(Map json) => - _$CustomItemFromJson(json); - - @JsonKey(name: 'available', includeIfNull: false) - final bool? available; - @JsonKey(name: 'description', includeIfNull: false, defaultValue: '') - final String? description; - @JsonKey(name: 'id', includeIfNull: false, defaultValue: '') - final String? id; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$CustomItemFromJson; - static const toJsonFactory = _$CustomItemToJson; - Map toJson() => _$CustomItemToJson(this); - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is CustomItem && - (identical(other.available, available) || - const DeepCollectionEquality() - .equals(other.available, available)) && - (identical(other.description, description) || - const DeepCollectionEquality() - .equals(other.description, description)) && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - int get hashCode => - const DeepCollectionEquality().hash(available) ^ - const DeepCollectionEquality().hash(description) ^ - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $CustomItemExtension on CustomItem { - CustomItem copyWith( - {bool? available, String? description, String? id, String? name}) { - return CustomItem( - available: available ?? this.available, - description: description ?? this.description, - id: id ?? this.id, - name: name ?? this.name); - } -} - -@JsonSerializable(explicitToJson: true) -class ListCustomItem { - ListCustomItem(); - - factory ListCustomItem.fromJson(Map json) => - _$ListCustomItemFromJson(json); - - static const fromJsonFactory = _$ListCustomItemFromJson; - static const toJsonFactory = _$ListCustomItemToJson; - Map toJson() => _$ListCustomItemToJson(this); - - @override - int get hashCode => runtimeType.hashCode; -} - -typedef $JsonFactory = T Function(Map json); - -class $CustomJsonDecoder { - $CustomJsonDecoder(this.factories); - - final Map factories; - - dynamic decode(dynamic entity) { - if (entity is Iterable) { - return _decodeList(entity); - } - - if (entity is T) { - return entity; - } - - if (entity is Map) { - return _decodeMap(entity); - } - - return entity; - } - - T _decodeMap(Map values) { - final jsonFactory = factories[T]; - if (jsonFactory == null || jsonFactory is! $JsonFactory) { - return throw "Could not find factory for type $T. Is '$T: $T.fromJsonFactory' included in the CustomJsonDecoder instance creation in bootstrapper.dart?"; - } - - return jsonFactory(values); - } - - List _decodeList(Iterable values) => - values.where((v) => v != null).map((v) => decode(v) as T).toList(); -} - -class $JsonSerializableConverter extends chopper.JsonConverter { - @override - chopper.Response convertResponse( - chopper.Response response) { - if (response.bodyString.isEmpty) { - // In rare cases, when let's say 204 (no content) is returned - - // we cannot decode the missing json with the result type specified - return chopper.Response(response.base, null, error: response.error); - } - - final jsonRes = super.convertResponse(response); - return jsonRes.copyWith( - body: $jsonDecoder.decode(jsonRes.body) as ResultType); - } -} - -final $jsonDecoder = $CustomJsonDecoder(ExampleSwaggerJsonDecoderMappings); - -// ignore: unused_element -String? _dateToJson(DateTime? date) { - if (date == null) { - return null; - } - - final year = date.year.toString(); - final month = date.month < 10 ? '0${date.month}' : date.month.toString(); - final day = date.day < 10 ? '0${date.day}' : date.day.toString(); - - return '$year-$month-$day'; -} diff --git a/example/lib/swagger_generated_code/example_swagger.swagger.g2.dart b/example/lib/swagger_generated_code/example_swagger.swagger.g2.dart deleted file mode 100644 index ad0b80b6..00000000 --- a/example/lib/swagger_generated_code/example_swagger.swagger.g2.dart +++ /dev/null @@ -1,66 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'example_swagger.swagger.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -Room _$RoomFromJson(Map json) { - return Room( - author: json['author'] as String? ?? '', - avatar: json['avatar'] as String? ?? '', - id: json['id'] as String? ?? '', - lastMessage: json['lastMessage'] as String? ?? '', - name: json['name'] as String? ?? '', - ); -} - -Map _$RoomToJson(Room instance) { - final val = {}; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('author', instance.author); - writeNotNull('avatar', instance.avatar); - writeNotNull('id', instance.id); - writeNotNull('lastMessage', instance.lastMessage); - writeNotNull('name', instance.name); - return val; -} - -CustomItem _$CustomItemFromJson(Map json) { - return CustomItem( - available: json['available'] as bool?, - description: json['description'] as String? ?? '', - id: json['id'] as String? ?? '', - name: json['name'] as String? ?? '', - ); -} - -Map _$CustomItemToJson(CustomItem instance) { - final val = {}; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('available', instance.available); - writeNotNull('description', instance.description); - writeNotNull('id', instance.id); - writeNotNull('name', instance.name); - return val; -} - -ListCustomItem _$ListCustomItemFromJson(Map json) { - return ListCustomItem(); -} - -Map _$ListCustomItemToJson(ListCustomItem instance) => - {}; diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 19fdc55a..4de6901f 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -13,6 +13,9 @@ const kBasicTypes = [ 'bool', 'boolean', 'num', + 'Object', + 'String', + 'Map', ]; const kChopperService = 'ChopperService'; diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index f40b0813..0daaa914 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -1,4 +1,3 @@ -import 'package:swagger_dart_code_generator/src/definitions.dart'; import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/extensions/file_name_extensions.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -28,31 +27,7 @@ class SwaggerAdditionsGenerator { ///Generated Map of all models generated by generator String generateConverterMappings( Map> buildExtensions, bool hasModels) { - if (!hasModels) { - return ''; - } - - final maps = StringBuffer(); - final imports = []; - buildExtensions.keys.forEach((String key) { - final className = - "${getClassNameFromFileName(key.split('/').last)}$converterClassEnding"; - - final fileName = getFileNameBase(key); - maps.writeln(' ...$className,'); - imports.add("import '$fileName.swagger.dart';"); - }); - - imports.sort(); - - final mapping = ''' -${imports.join('\n')} - -final Map)> $mappingVariableName = { -$maps}; -'''; - - return mapping; + return 'final Map)> $mappingVariableName = {};'; } ///Generated imports for concrete service @@ -71,6 +46,7 @@ $maps}; final chopperImports = buildOnlyModels ? '' : '''import 'package:chopper/chopper.dart'; +import 'client_mapping.dart'; import 'package:chopper/chopper.dart' as chopper;'''; final enumsImport = hasEnums @@ -195,7 +171,7 @@ class \$JsonSerializableConverter extends chopper.JsonConverter { } } -final \$jsonDecoder = \$CustomJsonDecoder(${fileName.pascalCase}JsonDecoderMappings); +final \$jsonDecoder = \$CustomJsonDecoder(generatedMapping); '''; } diff --git a/lib/src/code_generators/swagger_converter_generator.dart b/lib/src/code_generators/swagger_converter_generator.dart index 2e916780..5b9d1341 100644 --- a/lib/src/code_generators/swagger_converter_generator.dart +++ b/lib/src/code_generators/swagger_converter_generator.dart @@ -1,90 +1,4 @@ -import 'dart:convert'; -import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; -import 'package:swagger_dart_code_generator/src/definitions.dart'; -import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; -import 'package:recase/recase.dart'; -import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; -import 'constants.dart'; - class SwaggerConverterGenerator { - String generate(String dartCode, String fileName, GeneratorOptions options) { - return ''' -final Map)> ${fileName.pascalCase}$converterClassEnding = -{ -${_generateModelsMapping(dartCode, options)}};'''; - } - - String _generateModelsMapping(String dartCode, GeneratorOptions options) { - final result = []; - final dynamic map = jsonDecode(dartCode); - - final classes = getDefinitions(map); - - final classesFromResponses = - SwaggerModelsGenerator.getClassesFromResponses(dartCode, options); - - classes.addAll(classesFromResponses); - - if (classes.isNotEmpty) { - for (var i = 0; i < classes.keys.length; i++) { - final key = classes.keys.elementAt(i).toString(); - - final definition = classes[key]; - - if (definition['enum'] != null) { - continue; - } - - if (kBasicTypes.contains(definition['type'].toString().toLowerCase())) { - continue; - } - - if (definition['type'] == 'array' && - definition['items'] != null && - definition['items']['type'] == 'enum') { - continue; - } - - final validatedName = - SwaggerModelsGenerator.getValidatedClassName(key) + - options.modelPostfix; - - result.add('\t$validatedName: $validatedName.fromJsonFactory,'); - } - } - - final responses = getResponses(map); - if (responses.isNotEmpty) { - responses.keys.forEach((key) { - if (!result.contains(key)) { - final response = responses[key] as Map?; - - final content = response == null - ? null - : response['content'] as Map?; - - final firstContent = content == null || content.entries.isEmpty - ? null - : content.entries.first.value as Map?; - - final schema = firstContent == null - ? null - : firstContent['schema'] as Map?; - - if (schema != null && - content!.entries.length == 1 && - !schema.containsKey('\$ref')) { - final validatedName = SwaggerModelsGenerator.getValidatedClassName( - key.capitalize + options.modelPostfix); - result.add('\t$validatedName: $validatedName.fromJsonFactory,'); - } - } - }); - } - - return result.join('\n'); - } - Map getDefinitions(dynamic map) { if (map['definitions'] != null) { return map['definitions'] as Map? ?? {}; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 06004b7c..72972761 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -160,22 +160,51 @@ class SwaggerRequestsGenerator { .add(_getMethodAnnotation(requestType, path, hasOptionalBody)) ..returns = Reference(returns)); - if (_hasEnumProperties(method)) { - final privateMethod = _getPrivateMethod(method); - final publicMethod = _getPublicMethod(method); - methods.addAll([publicMethod, privateMethod]); - } else { - methods.add(method); - } + final allModels = _getAllMethodModels( + swaggerRoot, + swaggerRequest, + returnTypeName, + ); + + final privateMethod = _getPrivateMethod(method); + final publicMethod = _getPublicMethod(method, allModels); + methods.addAll([publicMethod, privateMethod]); }); }); return methods; } - bool _hasEnumProperties(Method method) { - return method.optionalParameters - .any((p) => p.type!.symbol!.startsWith('enums') == true); + List _getAllMethodModels( + SwaggerRoot root, + SwaggerRequest request, + String response, + ) { + final results = []; + + ///Models from parameters + request.parameters.forEach((parameter) { + final ref = parameter.anyRef; + + if (ref.isNotEmpty) { + final schema = root.allSchemas[ref.getUnformattedRef()]; + + if (schema == null || schema.type != kObject) { + return; + } + + results.add(ref.getRef()); + } + }); + + //Models from response + + final neededResponse = response.removeList(); + if (!kBasicTypes.contains(neededResponse)) { + results.add(neededResponse); + } + + return results.where((element) => element.isNotEmpty).toList(); } Method _getPrivateMethod(Method method) { @@ -197,7 +226,7 @@ class SwaggerRequestsGenerator { ); } - Method _getPublicMethod(Method method) { + Method _getPublicMethod(Method method, List allModels) { final parameters = method.optionalParameters.map((p) => p.copyWith(annotations: [])); @@ -207,12 +236,19 @@ class SwaggerRequestsGenerator { ..docs.addAll(method.docs) ..name = method.name ..returns = method.returns - ..body = _generatePublicMethodReturn(parameters, method.name!), + ..body = _generatePublicMethodCode( + parameters, + method.name!, + allModels, + ), ); } - Code _generatePublicMethodReturn( - Iterable parameters, String publicMethodName) { + Code _generatePublicMethodCode( + Iterable parameters, + String publicMethodName, + List allModels, + ) { final parametersListString = parameters.map((p) { if (p.type!.symbol!.startsWith('enums.')) { final enumName = @@ -222,8 +258,19 @@ class SwaggerRequestsGenerator { } return '${p.name} : ${p.name}'; }).join(', '); + if (allModels.isNotEmpty) { + print(allModels); + } + + var allModelsString = ''; + + allModels.toSet().forEach((model) { + allModelsString += + 'generatedMapping.putIfAbsent($model, () => $model.fromJsonFactory);\n'; + }); - return Code('return _$publicMethodName($parametersListString);'); + return Code( + '$allModelsString\nreturn _$publicMethodName($parametersListString);'); } Expression _getMethodAnnotation( @@ -822,3 +869,18 @@ class SwaggerRequestsGenerator { return ''; } } + +extension on SwaggerRequestParameter { + String get anyRef => schema?.ref ?? items?.ref ?? schema?.items?.ref ?? ref; +} + +extension on SwaggerSchema { + String get anyRef => schema?.ref ?? items?.ref ?? schema?.items?.ref ?? ref; +} + +extension on SwaggerRoot { + Map get allSchemas => { + ...definitions, + ...components?.schemas ?? {}, + }; +} diff --git a/lib/src/definitions.dart b/lib/src/definitions.dart deleted file mode 100644 index 575e2230..00000000 --- a/lib/src/definitions.dart +++ /dev/null @@ -1 +0,0 @@ -const String converterClassEnding = 'JsonDecoderMappings'; diff --git a/lib/src/extensions/string_extension.dart b/lib/src/extensions/string_extension.dart index b81a4a5a..1c812c6b 100644 --- a/lib/src/extensions/string_extension.dart +++ b/lib/src/extensions/string_extension.dart @@ -32,6 +32,8 @@ extension TypeExtension on String { String asList() => 'List<$this>'; + String removeList() => replaceAll('List<', '').replaceAll('>', ''); + String asEnum() => 'enums.$this'; String asFutureResponse() => 'Future>'; diff --git a/lib/src/swagger_code_generator.dart b/lib/src/swagger_code_generator.dart index 4f79fc7f..a09e0cb4 100644 --- a/lib/src/swagger_code_generator.dart +++ b/lib/src/swagger_code_generator.dart @@ -55,11 +55,6 @@ class SwaggerCodeGenerator { hasEnums, separateModels); - String generateConverter( - String dartCode, String fileName, GeneratorOptions options) => - _getSwaggerConverterGenerator(dartCode) - .generate(dartCode, fileName, options); - String generateResponses( String dartCode, String fileName, GeneratorOptions options) => _getSwaggerModelsGenerator(dartCode) diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 898c2ab4..4be90f32 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -96,9 +96,6 @@ class SwaggerDartCodeGenerator implements Builder { options.separateModels, ); - final converter = codeGenerator.generateConverter( - contents, getFileNameWithoutExtension(fileNameWithExtension), options); - final requests = codeGenerator.generateRequests( contents, getClassNameFromFileName(fileNameWithExtension), @@ -121,7 +118,6 @@ class SwaggerDartCodeGenerator implements Builder { _generateFileContent( imports, requests, - converter, options.separateModels ? '' : models, options.separateModels ? '' : responses, options.separateModels ? '' : requestBodies, @@ -169,7 +165,6 @@ class SwaggerDartCodeGenerator implements Builder { String _generateFileContent( String imports, String requests, - String converter, String models, String responses, String requestBodies, @@ -180,8 +175,6 @@ $imports ${options.buildOnlyModels ? '' : requests} -${options.withConverter && !options.buildOnlyModels ? converter : ''} - $models $responses diff --git a/test/generator_tests/converter_generator_test.dart b/test/generator_tests/converter_generator_test.dart deleted file mode 100644 index bc4bb782..00000000 --- a/test/generator_tests/converter_generator_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'package:swagger_dart_code_generator/src/code_generators/swagger_converter_generator.dart'; -import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; -import 'package:test/test.dart'; - -import '../converter_generator_definitions.dart'; - -void main() { - group('Converter generator tests', () { - final generator = SwaggerConverterGenerator(); - const fileName = 'file_name'; - - test('Should create fromJsonFactory for model', () { - final result = generator.generate( - model_with_parameters, - fileName, - GeneratorOptions(inputFolder: '', outputFolder: ''), - ); - - expect( - result, - contains( - 'ActiveOrderAndListSummary: ActiveOrderAndListSummary.fromJsonFactory')); - }); - - test( - 'Should not create fromJsonFactory for model with array enums parameters', - () { - final result = generator.generate(model_with_enunm_array_parameters_v2, - fileName, GeneratorOptions(inputFolder: '', outputFolder: '')); - - final isContains = result.contains( - 'ActiveOrderAndListSummary: ActiveOrderAndListSummary.fromJsonFactory'); - - expect(isContains, equals(false)); - }); - - test('Should create fromJsonFactory for model', () { - final result = generator.generate(model_with_parameters_v2, fileName, - GeneratorOptions(inputFolder: '', outputFolder: '')); - - expect( - result, - contains( - 'ActiveOrderAndListSummary: ActiveOrderAndListSummary.fromJsonFactory')); - }); - }); -} From fc1a8e7cee1aa4c49435d4ef8b53b663133357de Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 24 Nov 2021 12:03:52 +0300 Subject: [PATCH 15/39] Fix cases when refs are overriden --- example/build.yaml | 9 +++++++++ lib/src/code_generators/constants.dart | 4 +++- .../code_generators/swagger_requests_generator.dart | 11 ++++++++++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/example/build.yaml b/example/build.yaml index 62c21ecd..5decdba8 100644 --- a/example/build.yaml +++ b/example/build.yaml @@ -37,6 +37,15 @@ targets: - url: "/v2/channels" method: get overridden_value: "List" + - url: "/{country}/{lang}/events/segments/{segmentName}" + method: get + overridden_value: "Map" + - url: "/v1/titlePreferredInstance/{titleCrid}" + method: get + overridden_value: TitlePreferredInstance + - url: "/v2/detailscreen/{crid}" + method: get + overridden_value: "Map" default_header_values_map: - header_name: "X-Entitlements-Token" default_value: "X-Entitlements-Token" diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 4de6901f..0aead2dc 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -15,9 +15,11 @@ const kBasicTypes = [ 'num', 'Object', 'String', - 'Map', + kMap, ]; +const kMap = 'Map'; + const kChopperService = 'ChopperService'; const kChopperApi = 'ChopperApi'; const kResponse = 'Response'; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 72972761..0a100f76 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -204,7 +204,16 @@ class SwaggerRequestsGenerator { results.add(neededResponse); } - return results.where((element) => element.isNotEmpty).toList(); + return results.where((element) => _isValidModelName(element)).toList(); + } + + bool _isValidModelName(String modelName) { + if (modelName.isEmpty || + kBasicTypes.contains(modelName) || + modelName.startsWith(kMap)) { + return false; + } + return true; } Method _getPrivateMethod(Method method) { From e14ed6a9af17c7d2b4a3069e6968a089d9908106 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 14 Dec 2021 18:42:41 +0300 Subject: [PATCH 16/39] Fixed enum generation Changed int64 parsing to double --- lib/src/code_generators/constants.dart | 3 ++- lib/src/code_generators/swagger_requests_generator.dart | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 19fdc55a..13f7708b 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -21,6 +21,7 @@ const kResponse = 'Response'; const kRequestBody = 'RequestBody'; const kFutureResponse = 'Future'; const kString = 'string'; +const kInteger = 'integer'; const kUndefinedParameter = 'undefinedParameter'; const kResponses = '/responses/'; @@ -40,7 +41,7 @@ const kBasicTypesMap = { 'integer': 'int', 'int': 'int', 'int32': 'int', - 'int64': 'int', + 'int64': 'double', 'boolean': 'bool', 'bool': 'bool', 'string': 'String', diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 06004b7c..f762e257 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -363,6 +363,10 @@ class SwaggerRequestsGenerator { return parameter.schema!.ref.getRef().asEnum(); } + if (_isEnumRef(parameter.schema!.ref.getUnformattedRef(), root)) { + return parameter.schema!.ref.getRef().asEnum(); + } + if (parameter.schema!.items != null || parameter.schema!.type == kArray) { return (parameter.schema!.ref.getRef() + modelPostfix).asList(); } @@ -374,7 +378,7 @@ class SwaggerRequestsGenerator { return _mapParameterName(parameter.schema!.anyOf.first.type, ''); } - final neededType = parameter.type.isNotEmpty + var neededType = parameter.type.isNotEmpty ? parameter.type : parameter.schema?.type ?? kObject.pascalCase; @@ -515,7 +519,8 @@ class SwaggerRequestsGenerator { final neededSchema = schemas[neededSchemaKey]!; - if (neededSchema.type == kString && neededSchema.enumValues.isNotEmpty) { + if ((neededSchema.type == kString || neededSchema.type == kInteger) && + neededSchema.enumValues.isNotEmpty) { return true; } From 16d788e71e4976dd4bd50ab687b2ce495ec51b44 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 14 Dec 2021 18:53:40 +0300 Subject: [PATCH 17/39] Released 2.2.8 --- CHANGELOG.md | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d465d6e3..76896352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 2.2.8 + +* Fixed Issue ([#285](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/285)) +* Fixed generation of enum fields in requests +* Changed int64 parsing to double + # 2.2.7 * Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/264)) diff --git a/pubspec.yaml b/pubspec.yaml index 4218ae60..c6bba656 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.7 +version: 2.2.8 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 73d0ae5bd1058a31ca7ce6213e82134d01232031 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 15 Dec 2021 14:16:59 +0300 Subject: [PATCH 18/39] Added support int64 --- lib/src/code_generators/constants.dart | 4 +++- .../swagger_requests_generator.dart | 24 ++++++++++++------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 13f7708b..4af0761c 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -22,6 +22,8 @@ const kRequestBody = 'RequestBody'; const kFutureResponse = 'Future'; const kString = 'string'; const kInteger = 'integer'; +const kInt64 = 'int64'; +const kNum = 'num'; const kUndefinedParameter = 'undefinedParameter'; const kResponses = '/responses/'; @@ -41,7 +43,7 @@ const kBasicTypesMap = { 'integer': 'int', 'int': 'int', 'int32': 'int', - 'int64': 'double', + 'int64': 'num', 'boolean': 'bool', 'bool': 'bool', 'string': 'String', diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index f762e257..9f846fa3 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -339,19 +339,23 @@ class SwaggerRequestsGenerator { required String modelPostfix, required SwaggerRoot root, }) { + final format = parameter.schema?.format ?? ''; + if (parameter.inParameter == kHeader) { - return _mapParameterName(kString, ''); + return _mapParameterName(kString, format, ''); } else if (parameter.items?.enumValues.isNotEmpty == true || parameter.schema?.enumValues.isNotEmpty == true) { return _getEnumParameterTypeName( parameterName: parameter.name, path: path, requestType: requestType); } else if (parameter.items?.type.isNotEmpty == true) { - return _mapParameterName(parameter.items!.type, modelPostfix).asList(); + return _mapParameterName(parameter.items!.type, format, modelPostfix) + .asList(); } else if (parameter.items?.ref.isNotEmpty == true) { if (_isEnumRefParameter(parameter, root)) { return parameter.items!.ref.getRef().asEnum(); } - return _mapParameterName(parameter.items!.ref.getRef(), modelPostfix) + return _mapParameterName( + parameter.items!.ref.getRef(), format, modelPostfix) .asList(); } else if (parameter.schema?.items?.ref.isNotEmpty == true) { if (_isEnumRefParameter(parameter, root)) { @@ -373,19 +377,23 @@ class SwaggerRequestsGenerator { return (parameter.schema!.ref.getRef() + modelPostfix); } else if (parameter.schema?.type == kArray && parameter.schema?.items?.type.isNotEmpty == true) { - return _mapParameterName(parameter.schema!.items!.type, '').asList(); + return _mapParameterName(parameter.schema!.items!.type, format, '') + .asList(); } else if (parameter.schema?.anyOf.firstOrNull?.type.isNotEmpty == true) { - return _mapParameterName(parameter.schema!.anyOf.first.type, ''); + return _mapParameterName(parameter.schema!.anyOf.first.type, format, ''); } var neededType = parameter.type.isNotEmpty ? parameter.type : parameter.schema?.type ?? kObject.pascalCase; - return _mapParameterName(neededType, modelPostfix); + return _mapParameterName(neededType, format, modelPostfix); } - String _mapParameterName(String name, String modelPostfix) { + String _mapParameterName(String name, String format, String modelPostfix) { + if (name == kInteger && format == kInt64) { + return kNum; + } return kBasicTypesMap[name] ?? name.pascalCase + modelPostfix; } @@ -646,7 +654,7 @@ class SwaggerRequestsGenerator { return null; } - return _mapParameterName(mappedArrayType, modelPostfix).asList(); + return _mapParameterName(mappedArrayType, '', modelPostfix).asList(); } return kBasicTypesMap[responseType] ?? responseType + modelPostfix; From 850624fb957f897e8c42c14099822ae3f71324cf Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 15 Dec 2021 14:18:17 +0300 Subject: [PATCH 19/39] Updated changelog and pubspec --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76896352..84039a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 2.2.8 +* Fixed support of fields type integer and format int64 + +# 2.2.8 + * Fixed Issue ([#285](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/285)) * Fixed generation of enum fields in requests * Changed int64 parsing to double diff --git a/pubspec.yaml b/pubspec.yaml index c6bba656..303726b4 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.8 +version: 2.2.9 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 9139808178a7f3b09ef3aaaba0de1a12de4bd11d Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Thu, 16 Dec 2021 15:01:31 +0300 Subject: [PATCH 20/39] Fix for models int64 --- lib/src/code_generators/swagger_models_generator.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 822c5eb2..31a84aae 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -333,6 +333,10 @@ abstract class SwaggerModelsGenerator { switch (parameter['type'] as String?) { case 'integer': case 'int': + if (parameter['format'] == kInt64) { + return kNum; + } + return 'int'; case 'int32': case 'int64': return 'int'; From c575224bcdbddc8370985e82adfff52542df1d2a Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Thu, 16 Dec 2021 15:22:12 +0300 Subject: [PATCH 21/39] Updated changelog and pubspec --- CHANGELOG.md | 6 +++++- pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84039a5f..396b86de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ -# 2.2.8 +# 2.2.10 + +* Fixed support of int64 fields in Models + +# 2.2.9 * Fixed support of fields type integer and format int64 diff --git a/pubspec.yaml b/pubspec.yaml index 303726b4..89a82592 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.9 +version: 2.2.10 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 2a6f9cd6a6015e93ba8a4e5f31106e80294940b8 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 17 Dec 2021 12:39:03 +0300 Subject: [PATCH 22/39] Removed not needed file --- example/lib/swagger_generated_code/client_index.dart | 1 - 1 file changed, 1 deletion(-) delete mode 100644 example/lib/swagger_generated_code/client_index.dart diff --git a/example/lib/swagger_generated_code/client_index.dart b/example/lib/swagger_generated_code/client_index.dart deleted file mode 100644 index a12ba42e..00000000 --- a/example/lib/swagger_generated_code/client_index.dart +++ /dev/null @@ -1 +0,0 @@ -export 'pets_api.swagger.dart' show PetsApi; From 3f850d338b58087bcfb9490e062f9e2f42a9c2de Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 14:09:52 +0300 Subject: [PATCH 23/39] Fixed responses array of int --- .../swagger_requests_generator.dart | 11 ++++ lib/src/swagger_models/swagger_root.dart | 19 ++++++ lib/src/swagger_models/swagger_root.g2.dart | 64 ++++++++++--------- 3 files changed, 63 insertions(+), 31 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 4bdcc8ed..93cf7c89 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -830,9 +830,20 @@ class SwaggerRequestsGenerator { SwaggerModelsGenerator.getValidatedClassName(schemaItemsRef.getRef()) .withPostfix(modelPostfix) .asList(); + return result; } + if (content.schema?.type == kArray) { + final itemsType = content.schema?.items?.type ?? ''; + final itemsFormat = content.schema?.items?.format ?? ''; + + if (itemsType.isNotEmpty) { + final parameterType = _mapParameterName(itemsType, itemsFormat, ''); + return parameterType.asList(); + } + } + final contentSchemaType = content.schema?.type ?? ''; if (contentSchemaType.isNotEmpty == true) { return kBasicTypesMap[contentSchemaType]; diff --git a/lib/src/swagger_models/swagger_root.dart b/lib/src/swagger_models/swagger_root.dart index 5306d9ba..c4c525b4 100644 --- a/lib/src/swagger_models/swagger_root.dart +++ b/lib/src/swagger_models/swagger_root.dart @@ -22,6 +22,7 @@ class SwaggerRoot { required this.schemes, required this.parameters, required this.definitions, + required this.securityDefinitions, }); @JsonKey(name: 'info') @@ -51,12 +52,30 @@ class SwaggerRoot { @JsonKey(name: 'components') SwaggerComponents? components; + @JsonKey(name: 'securityDefinitions', fromJson: _mapSecurityDefinitions) + Map securityDefinitions; + Map toJson() => _$SwaggerRootToJson(this); factory SwaggerRoot.fromJson(Map json) => _$SwaggerRootFromJson(json); } +Map _mapSecurityDefinitions( + Map? definitions) { + if (definitions == null) { + return {}; + } + + final definitionsArray = definitions.map((key, value) { + final typedValue = value as Map; + + return MapEntry(key, SwaggerRequestParameter.fromJson(typedValue)); + }); + + return definitionsArray; +} + Map _mapPaths(Map? paths) { if (paths == null) { return {}; diff --git a/lib/src/swagger_models/swagger_root.g2.dart b/lib/src/swagger_models/swagger_root.g2.dart index 242e8ade..b7530f78 100644 --- a/lib/src/swagger_models/swagger_root.g2.dart +++ b/lib/src/swagger_models/swagger_root.g2.dart @@ -6,37 +6,38 @@ part of 'swagger_root.dart'; // JsonSerializableGenerator // ************************************************************************** -SwaggerRoot _$SwaggerRootFromJson(Map json) { - return SwaggerRoot( - basePath: json['basePath'] as String? ?? '', - components: json['components'] == null - ? null - : SwaggerComponents.fromJson( - json['components'] as Map), - info: json['info'] == null - ? null - : SwaggerInfo.fromJson(json['info'] as Map), - host: json['host'] as String? ?? '', - paths: _mapPaths(json['paths'] as Map?), - tags: (json['tags'] as List?) - ?.map((e) => SwaggerTag.fromJson(e as Map)) - .toList() ?? - [], - schemes: - (json['schemes'] as List?)?.map((e) => e as String).toList() ?? - [], - parameters: (json['parameters'] as Map?)?.map( - (k, e) => MapEntry( - k, SwaggerRequestParameter.fromJson(e as Map)), - ) ?? - {}, - definitions: (json['definitions'] as Map?)?.map( - (k, e) => - MapEntry(k, SwaggerSchema.fromJson(e as Map)), - ) ?? - {}, - ); -} +SwaggerRoot _$SwaggerRootFromJson(Map json) => SwaggerRoot( + basePath: json['basePath'] as String? ?? '', + components: json['components'] == null + ? null + : SwaggerComponents.fromJson( + json['components'] as Map), + info: json['info'] == null + ? null + : SwaggerInfo.fromJson(json['info'] as Map), + host: json['host'] as String? ?? '', + paths: _mapPaths(json['paths'] as Map?), + tags: (json['tags'] as List?) + ?.map((e) => SwaggerTag.fromJson(e as Map)) + .toList() ?? + [], + schemes: (json['schemes'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + parameters: (json['parameters'] as Map?)?.map( + (k, e) => MapEntry( + k, SwaggerRequestParameter.fromJson(e as Map)), + ) ?? + {}, + definitions: (json['definitions'] as Map?)?.map( + (k, e) => + MapEntry(k, SwaggerSchema.fromJson(e as Map)), + ) ?? + {}, + securityDefinitions: _mapSecurityDefinitions( + json['securityDefinitions'] as Map?), + ); Map _$SwaggerRootToJson(SwaggerRoot instance) => { @@ -49,4 +50,5 @@ Map _$SwaggerRootToJson(SwaggerRoot instance) => 'definitions': instance.definitions, 'parameters': instance.parameters, 'components': instance.components, + 'securityDefinitions': instance.securityDefinitions, }; From c6e9cb39bf19bddc6b7eef65209b319c8634b1cf Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 14:19:19 +0300 Subject: [PATCH 24/39] Reverted analysis options --- analysis_options.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/analysis_options.yaml b/analysis_options.yaml index 53f872bd..b429b96c 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -6,6 +6,8 @@ analyzer: strong-mode: implicit-casts: false exclude: + - example/**/*.dart + - lib/**/*.g2.dart linter: rules: - type_annotate_public_apis From b987918aa1dc7e41affa542a2384f1c121360450 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 14:19:50 +0300 Subject: [PATCH 25/39] Updated changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index facce2ba..e17922e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ # 2.2.5 * Fixed Issue ([#265](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/265)) +* Fixed Issue ([#289](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/289)) * Fixed Issue ([#275](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/275)) * Returned possibility to use operationId for request name * Added generation of requestBodies integrated to requests, when it's complex model From 2c20a3b14d7dbb2a1ddc49699035e25d1e73a3d3 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 14:20:56 +0300 Subject: [PATCH 26/39] Updated version --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 89a82592..77bc2a1a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.2.10 +version: 2.3.0 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From a1a93c3eaf88bb4167ccf9f6945a71f7d42a8b6e Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 14:38:06 +0300 Subject: [PATCH 27/39] Fixed tests --- .../additions_generator_test.dart | 30 ------------------- .../requests_generator_test.dart | 4 --- 2 files changed, 34 deletions(-) diff --git a/test/generator_tests/additions_generator_test.dart b/test/generator_tests/additions_generator_test.dart index eb650a22..35c9a30b 100644 --- a/test/generator_tests/additions_generator_test.dart +++ b/test/generator_tests/additions_generator_test.dart @@ -1,21 +1,10 @@ import 'package:swagger_dart_code_generator/src/code_generators/swagger_additions_generator.dart'; -import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:test/test.dart'; void main() { group('Additions generator tests', () { final generator = SwaggerAdditionsGenerator(); - test('Should generate mapping for files', () { - final result = generator.generateConverterMappings(>{ - 'someFile.dart': ['someFile.swagger.dart'], - 'secondFile.dart': ['secondFile.swagger.dart'] - }, true); - - expect(result, contains('...SomeFileJsonDecoderMappings')); - expect(result, contains('...SecondFileJsonDecoderMappings')); - }); - test('Should generate correct imports', () { final result = generator.generateImportsContent( 'swagger.fileName', true, false, false, false); @@ -43,25 +32,6 @@ void main() { result, contains("export 'secondFile.dart.dart' show SecondFile;")); }); }); - - group('Test for generateCustomJsonConverter', () { - final generator = SwaggerAdditionsGenerator(); - test('Should generate custom json converter', () { - const fileName = 'example_swagger'; - const expectedResult = - 'CustomJsonDecoder(ExampleSwaggerJsonDecoderMappings)'; - final result = generator.generateCustomJsonConverter( - fileName, - GeneratorOptions( - inputFolder: '', - outputFolder: '', - ), - ); - - expect(result, contains(expectedResult)); - }); - }); - group('Test for generateDateToJson', () { final generator = SwaggerAdditionsGenerator(); test('Should dateToJson with parameter', () { diff --git a/test/generator_tests/requests_generator_test.dart b/test/generator_tests/requests_generator_test.dart index 5ef1684c..b1b10f63 100644 --- a/test/generator_tests/requests_generator_test.dart +++ b/test/generator_tests/requests_generator_test.dart @@ -48,10 +48,6 @@ void main() { expect(result2, contains('Future>')); expect(result, contains('Future> carsGet')); expect(result, contains('Future> carsPost')); - expect( - result, - contains( - 'Future> carsAdditionalPut({@Body() required Object? body});')); }); }); } From a1b6bd3da55430888ad0c1bac9693592c4c2023a Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Wed, 22 Dec 2021 15:05:15 +0300 Subject: [PATCH 28/39] Fixed analyser issues --- lib/src/code_generators/swagger_additions_generator.dart | 1 - lib/src/code_generators/swagger_requests_generator.dart | 4 ---- lib/src/swagger_code_generator.dart | 4 ---- 3 files changed, 9 deletions(-) diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index 0daaa914..2bb9afa5 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -1,4 +1,3 @@ -import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/extensions/file_name_extensions.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 93cf7c89..cb636463 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -907,10 +907,6 @@ extension on SwaggerRequestParameter { String get anyRef => schema?.ref ?? items?.ref ?? schema?.items?.ref ?? ref; } -extension on SwaggerSchema { - String get anyRef => schema?.ref ?? items?.ref ?? schema?.items?.ref ?? ref; -} - extension on SwaggerRoot { Map get allSchemas => { ...definitions, diff --git a/lib/src/swagger_code_generator.dart b/lib/src/swagger_code_generator.dart index a09e0cb4..6f1fbad6 100644 --- a/lib/src/swagger_code_generator.dart +++ b/lib/src/swagger_code_generator.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_additions_generator.dart'; -import 'package:swagger_dart_code_generator/src/code_generators/swagger_converter_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_enums_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_requests_generator.dart'; @@ -93,9 +92,6 @@ class SwaggerCodeGenerator { SwaggerAdditionsGenerator _getSwaggerAdditionsGenerator(String dartCode) => SwaggerAdditionsGenerator(); - SwaggerConverterGenerator _getSwaggerConverterGenerator(String dartCode) => - SwaggerConverterGenerator(); - SwaggerEnumsGenerator _getSwaggerEnumsGenerator(String dartCode) => _enumsMap[_getApiVersion(dartCode)]!; From b6eb45b0cbeb274bed058eb80aab052ffe9d973e Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Thu, 23 Dec 2021 12:00:01 +0300 Subject: [PATCH 29/39] Fixed issue #291 --- lib/src/code_generators/swagger_enums_generator.dart | 1 - lib/src/code_generators/swagger_requests_generator.dart | 3 --- 2 files changed, 4 deletions(-) diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index 54bc049f..54100d43 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -218,7 +218,6 @@ $enumMap } String getEnumValuesContent(List enumValues) { - print(enumValues); final result = []; final resultStrings = []; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index cb636463..f0c3b691 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -267,9 +267,6 @@ class SwaggerRequestsGenerator { } return '${p.name} : ${p.name}'; }).join(', '); - if (allModels.isNotEmpty) { - print(allModels); - } var allModelsString = ''; From f495829b7e74a2f0ce3684ffd526643eb6f468a0 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Thu, 23 Dec 2021 12:00:44 +0300 Subject: [PATCH 30/39] updated changelog and pubcpec --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc6825ae..64bec80a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.3.1 + +* * Fixed Issue ([#291](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/291)) + # 2.3.0 * Fixed Issue ([#289](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/289)) diff --git a/pubspec.yaml b/pubspec.yaml index 77bc2a1a..259bd727 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.3.0 +version: 2.3.1 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 39f4a7e891f4ea93c10437903ad926ff8b249678 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 24 Dec 2021 14:04:12 +0300 Subject: [PATCH 31/39] Added parsing of security for requests --- .../requests/swagger_request.dart | 17 ++++ .../requests/swagger_request.g2.dart | 84 +++++++++---------- 2 files changed, 59 insertions(+), 42 deletions(-) diff --git a/lib/src/swagger_models/requests/swagger_request.dart b/lib/src/swagger_models/requests/swagger_request.dart index fe6c1ddd..2bfa48d9 100644 --- a/lib/src/swagger_models/requests/swagger_request.dart +++ b/lib/src/swagger_models/requests/swagger_request.dart @@ -16,6 +16,7 @@ class SwaggerRequest { this.responses = const {}, this.parameters = const [], this.produces = const [], + this.security = const [], this.requestBody, }); @@ -37,6 +38,9 @@ class SwaggerRequest { @JsonKey(name: 'responses', defaultValue: {}) Map responses; + @JsonKey(name: 'security', fromJson: _securityFromJson) + List security; + @JsonKey(name: 'parameters', defaultValue: []) List parameters; @@ -92,3 +96,16 @@ class RequestContent { factory RequestContent.fromJson(Map json) => _$RequestContentFromJson(json); } + +List _securityFromJson(List? map) { + if (map == null) { + return []; + } + + final result = map + .map((e) => (e as Map?)?.keys) + .expand((ee) => ee?.toList() ?? []) + .toList(); + + return result; +} diff --git a/lib/src/swagger_models/requests/swagger_request.g2.dart b/lib/src/swagger_models/requests/swagger_request.g2.dart index 785668b7..0a930a3f 100644 --- a/lib/src/swagger_models/requests/swagger_request.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request.g2.dart @@ -6,34 +6,36 @@ part of 'swagger_request.dart'; // JsonSerializableGenerator // ************************************************************************** -SwaggerRequest _$SwaggerRequestFromJson(Map json) { - return SwaggerRequest( - summary: json['summary'] as String? ?? '', - description: json['description'] as String? ?? '', - operationId: json['operationId'] as String? ?? '', - consumes: (json['consumes'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - responses: (json['responses'] as Map?)?.map( - (k, e) => - MapEntry(k, SwaggerResponse.fromJson(e as Map)), - ) ?? - {}, - parameters: (json['parameters'] as List?) - ?.map((e) => - SwaggerRequestParameter.fromJson(e as Map)) - .toList() ?? - [], - produces: (json['produces'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - requestBody: json['requestBody'] == null - ? null - : RequestBody.fromJson(json['requestBody'] as Map), - ); -} +SwaggerRequest _$SwaggerRequestFromJson(Map json) => + SwaggerRequest( + summary: json['summary'] as String? ?? '', + description: json['description'] as String? ?? '', + operationId: json['operationId'] as String? ?? '', + consumes: (json['consumes'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + responses: (json['responses'] as Map?)?.map( + (k, e) => MapEntry( + k, SwaggerResponse.fromJson(e as Map)), + ) ?? + {}, + parameters: (json['parameters'] as List?) + ?.map((e) => + SwaggerRequestParameter.fromJson(e as Map)) + .toList() ?? + [], + produces: (json['produces'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + security: json['security'] == null + ? const [] + : _securityFromJson(json['security'] as List?), + requestBody: json['requestBody'] == null + ? null + : RequestBody.fromJson(json['requestBody'] as Map), + ); Map _$SwaggerRequestToJson(SwaggerRequest instance) => { @@ -43,30 +45,28 @@ Map _$SwaggerRequestToJson(SwaggerRequest instance) => 'consumes': instance.consumes, 'produces': instance.produces, 'responses': instance.responses, + 'security': instance.security, 'parameters': instance.parameters, 'requestBody': instance.requestBody, }; -RequestBody _$RequestBodyFromJson(Map json) { - return RequestBody( - content: _contentFromJson(json['content'] as Map?), - ref: json['\$ref'] as String? ?? '', - ); -} +RequestBody _$RequestBodyFromJson(Map json) => RequestBody( + content: _contentFromJson(json['content'] as Map?), + ref: json[r'$ref'] as String? ?? '', + ); Map _$RequestBodyToJson(RequestBody instance) => { 'content': instance.content, - '\$ref': instance.ref, + r'$ref': instance.ref, }; -RequestContent _$RequestContentFromJson(Map json) { - return RequestContent( - schema: json['schema'] == null - ? null - : SwaggerSchema.fromJson(json['schema'] as Map), - ); -} +RequestContent _$RequestContentFromJson(Map json) => + RequestContent( + schema: json['schema'] == null + ? null + : SwaggerSchema.fromJson(json['schema'] as Map), + ); Map _$RequestContentToJson(RequestContent instance) => { From 56882c96e2955131e8fd7861d417363750375d5c Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 24 Dec 2021 14:21:49 +0300 Subject: [PATCH 32/39] Fixed num parsing as Num --- lib/src/code_generators/constants.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 095e96f1..4f7d4517 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -55,6 +55,7 @@ const kBasicTypesMap = { 'file': 'List', 'number': 'num', 'object': 'Object', + 'num': 'num', }; const kObject = 'object'; From c2e44121477236f42857576a89fc6d9cbd60b7e5 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 24 Dec 2021 14:29:08 +0300 Subject: [PATCH 33/39] Implemented security keys definition --- .../code_generators/swagger_requests_generator.dart | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index cb636463..018ce325 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -467,9 +467,15 @@ class SwaggerRequestsGenerator { definedParameters.addAll(root.parameters); definedParameters.addAll(root.components?.parameters ?? {}); - final parameters = [...swaggerRequest.parameters, ...swaggerPath.parameters] - .map((par) => definedParameters[par.ref.split('/').last] ?? par) - .toList(); + final securityParameters = swaggerRequest.security + .map((e) => root.securityDefinitions[e]) + .whereNotNull(); + + final parameters = [ + ...swaggerRequest.parameters, + ...swaggerPath.parameters, + ...securityParameters, + ].map((par) => definedParameters[par.ref.split('/').last] ?? par).toList(); final result = parameters .where((swaggerParameter) => From 76073dba90d0ea590a5dd6dc1ff1e177e789b17f Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 24 Dec 2021 14:50:31 +0300 Subject: [PATCH 34/39] Removed not needed prints --- lib/src/code_generators/swagger_requests_generator.dart | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 018ce325..51fe753b 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -267,9 +267,6 @@ class SwaggerRequestsGenerator { } return '${p.name} : ${p.name}'; }).join(', '); - if (allModels.isNotEmpty) { - print(allModels); - } var allModelsString = ''; From d1d056e445169d87cfaa073649d447caae5c4d07 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Fri, 24 Dec 2021 14:52:10 +0300 Subject: [PATCH 35/39] Updated changelog and pubspec --- CHANGELOG.md | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b958cf42..2d280450 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 2.3.2 + +* Fixed Issue ([#290](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/290)) +* Fixed cases with Num instead of num in responses +* Removed not needed prints + # 2.3.1 * Fixed Issue ([#291](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/291)) diff --git a/pubspec.yaml b/pubspec.yaml index 259bd727..cd0573e8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.3.1 +version: 2.3.2 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 84450378c0dd7a08bca23bccfb47d019646703f4 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Mon, 10 Jan 2022 14:18:04 +0300 Subject: [PATCH 36/39] Removed use_inheritance field --- CHANGELOG.md | 5 +++++ lib/src/code_generators/swagger_models_generator.dart | 4 +--- lib/src/models/generator_options.dart | 4 ---- lib/src/models/generator_options.g2.dart | 2 -- pubspec.yaml | 2 +- 5 files changed, 7 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d280450..8b9c70ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.3.3 + +* Fixed Issue ([#297](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/297)) +* Removed use_inheritance option. Inheritance is supported by copy-pasting parent fields + # 2.3.2 * Fixed Issue ([#290](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/290)) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 31a84aae..f4bfe0d0 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1042,8 +1042,6 @@ List ${neededName.camelCase}ListFromJson( GeneratorOptions options) { final properties = getModelProperties(map, schemas); - var extendsString = options.useInheritance ? getExtendsString(map) : ''; - final generatedConstructorProperties = generateConstructorPropertiesContent( className, properties, @@ -1079,7 +1077,7 @@ List ${neededName.camelCase}ListFromJson( final generatedClass = ''' @JsonSerializable(explicitToJson: true) -class $validatedClassName $extendsString{ +class $validatedClassName { \t$validatedClassName($generatedConstructorProperties);\n \tfactory $validatedClassName.fromJson(Map json) => _\$${validatedClassName}FromJson(json);\n $generatedProperties diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 1074d046..fa772383 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -20,7 +20,6 @@ class GeneratorOptions { this.enumsCaseSensitive = true, this.useRequiredAttributeForHeaders = true, this.usePathForRequestNames = true, - this.useInheritance = true, this.includeIfNull, this.modelPostfix = '', this.includePaths = const [], @@ -49,9 +48,6 @@ class GeneratorOptions { @JsonKey(defaultValue: false) final bool ignoreHeaders; - @JsonKey(defaultValue: true) - final bool useInheritance; - @JsonKey(defaultValue: false) final bool enumsCaseSensitive; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 6f4c6033..a6fbdf01 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -38,7 +38,6 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( json['use_required_attribute_for_headers'] as bool? ?? true, usePathForRequestNames: json['use_path_for_request_names'] as bool? ?? true, - useInheritance: json['use_inheritance'] as bool? ?? true, includeIfNull: json['include_if_null'] as bool?, modelPostfix: json['model_postfix'] as String? ?? '', includePaths: (json['include_paths'] as List?) @@ -60,7 +59,6 @@ Map _$GeneratorOptionsToJson(GeneratorOptions instance) => 'use_required_attribute_for_headers': instance.useRequiredAttributeForHeaders, 'ignore_headers': instance.ignoreHeaders, - 'use_inheritance': instance.useInheritance, 'enums_case_sensitive': instance.enumsCaseSensitive, 'include_if_null': instance.includeIfNull, 'input_folder': instance.inputFolder, diff --git a/pubspec.yaml b/pubspec.yaml index cd0573e8..d2968714 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.3.2 +version: 2.3.3 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 9a19d7a19c32caae3ddfff6801d7058d97b6a83b Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Mon, 10 Jan 2022 14:24:19 +0300 Subject: [PATCH 37/39] Removed outdated tests --- .../models_generator_test.dart | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 100b4bcb..ed0387d3 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -679,27 +679,6 @@ void main() { }); }); - group('getModelInheritedProperties', () { - test('Should generate 2 levels of inheritance', () { - final result = generator.generate(model_with_inheritance, 'MyClass', - GeneratorOptions(inputFolder: '', outputFolder: '')); - - expect( - result, contains('class ExtendedErrorModel extends BasicErrorModel')); - }); - - test('Should generate 3 levels of inheritance', () { - final result = generator.generate(model_with_inheritance_3_levels, - 'MyClass', GeneratorOptions(inputFolder: '', outputFolder: '')); - - expect(result, - contains('class MostExtendedErrorModel extends ExtendedErrorModel')); - - expect( - result, contains('class ExtendedErrorModel extends BasicErrorModel')); - }); - }); - group('Tests for getValidatedClassName', () { test('Should', () { final result = SwaggerModelsGenerator.getValidatedClassName('Request'); From c519d4701a62c597caeb6e1f0671adf981a22ba0 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 11 Jan 2022 15:03:35 +0300 Subject: [PATCH 38/39] Implemented integer enums support --- lib/src/code_generators/constants.dart | 2 + .../swagger_enums_generator.dart | 41 +++++++++++++++---- .../generator_tests/enums_generator_test.dart | 3 +- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 4f7d4517..963372fe 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -31,6 +31,8 @@ const kInt64 = 'int64'; const kNum = 'num'; const kUndefinedParameter = 'undefinedParameter'; +const kIntegerTypes = [kInteger, kInt64, kNum]; + const kResponses = '/responses/'; //Request types diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index 54100d43..b0888c71 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'package:recase/recase.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; import 'package:swagger_dart_code_generator/src/exception_words.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; @@ -182,8 +183,16 @@ $enumsFromRequestBodies swaggerRequestParameter.items?.enumValues ?? []; + final isInteger = + kIntegerTypes.contains(swaggerRequestParameter.schema?.type) || + kIntegerTypes.contains(swaggerRequestParameter.items?.type); + if (enumValues.isNotEmpty) { - final enumContent = generateEnumContent(name, enumValues); + final enumContent = generateEnumContent( + name, + enumValues, + isInteger, + ); result.writeln(enumContent); enumNames.add(swaggerRequestParameter.name); @@ -195,8 +204,15 @@ $enumsFromRequestBodies return result.toString(); } - String generateEnumContent(String enumName, List enumValues) { - final enumValuesContent = getEnumValuesContent(enumValues); + String generateEnumContent( + String enumName, + List enumValues, + bool isInteger, + ) { + final enumValuesContent = getEnumValuesContent( + enumValues: enumValues, + isInteger: isInteger, + ); final enumMap = ''' \n\tconst \$${enumName}Map = { @@ -217,7 +233,10 @@ $enumMap return result; } - String getEnumValuesContent(List enumValues) { + String getEnumValuesContent({ + required List enumValues, + required bool isInteger, + }) { final result = []; final resultStrings = []; @@ -229,8 +248,14 @@ $enumMap } result.add(validatedValue); - resultStrings.add( - "\t@JsonValue('${value.replaceAll("\$", "\\\$")}')\n\t$validatedValue"); + + if (isInteger) { + resultStrings.add( + "\t@JsonValue(${value.replaceAll("\$", "\\\$")})\n\t$validatedValue"); + } else { + resultStrings.add( + "\t@JsonValue('${value.replaceAll("\$", "\\\$")}')\n\t$validatedValue"); + } }); return resultStrings.join(',\n'); @@ -363,10 +388,12 @@ $enumMap }; '''; + final isInteger = kIntegerTypes.contains(map['type']); + return """ enum ${enumName.capitalize} { \t@JsonValue('$defaultEnumValueName')\n $defaultEnumValueName, -${getEnumValuesContent(enumValues)} +${getEnumValuesContent(enumValues: enumValues, isInteger: isInteger)} } $enumMap diff --git a/test/generator_tests/enums_generator_test.dart b/test/generator_tests/enums_generator_test.dart index 6059fa1a..c968f838 100644 --- a/test/generator_tests/enums_generator_test.dart +++ b/test/generator_tests/enums_generator_test.dart @@ -38,7 +38,8 @@ void main() { test('Should generate enum values', () { final values = ['file_sup']; const output = "\t@JsonValue('file_sup')\n\tfileSup"; - final result = generator.getEnumValuesContent(values); + final result = + generator.getEnumValuesContent(enumValues: values, isInteger: false); expect(result, contains(output)); }); From c1148605f572298b13e0e4f114d1d11cca769eb8 Mon Sep 17 00:00:00 2001 From: uladzimir_paliukhovich <> Date: Tue, 11 Jan 2022 15:05:51 +0300 Subject: [PATCH 39/39] Updated changelog and pubspec --- CHANGELOG.md | 5 +++++ pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b9c70ad..fb23fcc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.3.4 + +* Fixed Issue ([#268](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/268)) +* Added support of integer enum values + # 2.3.3 * Fixed Issue ([#297](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/297)) diff --git a/pubspec.yaml b/pubspec.yaml index d2968714..d8099849 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.3.3 +version: 2.3.4 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator