From 2c826d80e5e0f73e192dca73d89f34c61621c937 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 14:18:20 +0300 Subject: [PATCH 01/67] Fixed some issues --- .../swagger_models_generator.dart | 2 +- .../swagger_requests_generator.dart | 187 +++++++++--------- lib/src/models/generator_options.g2.dart | 2 +- 3 files changed, 90 insertions(+), 101 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index cacd6fa1..14e4bcbb 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1230,7 +1230,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr entityMap.forEach((key, value) { var fieldName = generateFieldName( getParameterName( - getValidatedClassName(key).asParameterName(), propertyNames), + getValidatedParameterName(key).asParameterName(), propertyNames), ); propertyNames.add(fieldName); diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index ab3d7395..54034d22 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -22,7 +22,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { @override GeneratorOptions get options => _options; - SwaggerRequestsGenerator(this._options,); + SwaggerRequestsGenerator( + this._options, + ); String generate({ required SwaggerRoot swaggerRoot, @@ -40,10 +42,12 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return service.accept(DartEmitter()).toString(); } - Class _generateService(SwaggerRoot swaggerRoot, - List allEnums, - String className, - String fileName,) { + Class _generateService( + SwaggerRoot swaggerRoot, + List allEnums, + String className, + String fileName, + ) { final allMethodsContent = _getAllMethodsContent( swaggerRoot: swaggerRoot, allEnums: allEnums, @@ -56,8 +60,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ); return Class( - (c) => - c + (c) => c ..methods.addAll([ _generateCreateMethod(className, chopperClient), ...allMethodsContent @@ -72,28 +75,24 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { Method _generateCreateMethod(String className, String body) { return Method( - (m) => - m + (m) => m ..returns = Reference(className) ..name = 'create' ..static = true ..optionalParameters.add(Parameter( - (p) => - p + (p) => p ..named = true ..type = Reference('ChopperClient?') ..name = 'client', )) ..optionalParameters.add(Parameter( - (p) => - p + (p) => p ..named = true ..type = Reference('Authenticator?') ..name = 'authenticator', )) ..optionalParameters.add(Parameter( - (p) => - p + (p) => p ..named = true ..type = Reference('Converter?') ..name = 'converter', @@ -105,8 +104,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..name = 'baseUrl', )) ..optionalParameters.add(Parameter( - (p) => - p + (p) => p ..named = true ..type = Reference('Iterable?') ..name = 'interceptors', @@ -179,7 +177,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { returns = '${options.customReturnType}<$innerResponseType>'; } else { - returns = returnTypeName.isEmpty ? kFutureResponse : returnTypeName.asFutureResponse(); + returns = returnTypeName.isEmpty + ? kFutureResponse + : returnTypeName.asFutureResponse(); } final hasOptionalBody = @@ -191,8 +191,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .any((p0) => p0.call([]).toString().contains('symbol=Part')); }); - final method = Method((m) => - m + final method = Method((m) => m ..optionalParameters.addAll(parameters) ..docs.add(_getCommentsForMethod( methodDescription: swaggerRequest.summary, @@ -219,9 +218,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return methods; } - List _getAllMethodModels(SwaggerRoot root, - SwaggerRequest request, - String response,) { + List _getAllMethodModels( + SwaggerRoot root, + SwaggerRequest request, + String response, + ) { final results = []; ///Models from parameters @@ -372,8 +373,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }); return Method( - (m) => - m + (m) => m ..optionalParameters.addAll(parameters) ..docs.addAll(method.docs) ..name = '_${method.name}' @@ -384,11 +384,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { Method _getPublicMethod(Method method, List allModels) { final parameters = - method.optionalParameters.map((p) => p.copyWith(annotations: [])); + method.optionalParameters.map((p) => p.copyWith(annotations: [])); return Method( - (m) => - m + (m) => m ..optionalParameters.addAll(parameters) ..docs.addAll(method.docs) ..name = method.name @@ -401,9 +400,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ); } - Code _generatePublicMethodCode(Iterable parameters, - String publicMethodName, - List allModels,) { + Code _generatePublicMethodCode( + Iterable parameters, + String publicMethodName, + List allModels, + ) { final parametersListString = parameters.map((p) { if (p.type!.symbol!.startsWith('enums.')) { return '${p.name} : ${p.name}?.value?.toString()'; @@ -411,9 +412,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (p.type!.symbol!.startsWith('List $model.fromJsonFactory);\n'; + 'generatedMapping.putIfAbsent($model, () => $model.fromJsonFactory);\n'; }); return Code( '$allModelsString\nreturn _$publicMethodName($parametersListString);'); } - List _getMethodAnnotation(String requestType, - String path, - bool hasOptionalBody, - bool isMultipart,) { + List _getMethodAnnotation( + String requestType, + String path, + bool hasOptionalBody, + bool isMultipart, + ) { return [ refer(requestType.pascalCase).call( [], @@ -457,11 +458,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required Map componentsParameters, }) { final parametersComments = parameters - .map((SwaggerRequestParameter parameter) => - _createSummaryParameters( - parameter, - componentsParameters, - )); + .map((SwaggerRequestParameter parameter) => _createSummaryParameters( + parameter, + componentsParameters, + )); final formattedDescription = methodDescription.split('\n').join('\n///'); @@ -470,8 +470,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .join('\n'); } - String _createSummaryParameters(SwaggerRequestParameter parameter, - Map componentsParameters,) { + String _createSummaryParameters( + SwaggerRequestParameter parameter, + Map componentsParameters, + ) { final neededParameter = componentsParameters[parameter.ref.getUnformattedRef()] ?? parameter; @@ -497,7 +499,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { case kBody: return refer(kBody.pascalCase).call([]); default: - //https://github.com/lejard-h/chopper/issues/295 + //https://github.com/lejard-h/chopper/issues/295 return refer(parameter.inParameter.pascalCase) .call([literalString(parameter.name.replaceAll('\$', ''))]); } @@ -510,11 +512,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }) { final pathString = path .split('/') - .map((e) => - e - .replaceAll('}', '') - .replaceAll('{', '') - .pascalCase) + .map((e) => e.replaceAll('}', '').replaceAll('{', '').pascalCase) .join(); final result = getValidatedClassName( @@ -523,8 +521,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return result.asEnum(); } - bool _isEnumRefParameter(SwaggerRequestParameter parameter, - SwaggerRoot root) { + bool _isEnumRefParameter( + SwaggerRequestParameter parameter, SwaggerRoot root) { final schemas = root.components?.schemas ?? {}; schemas.addAll(root.definitions); @@ -534,7 +532,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { parameter.items?.ref.getUnformattedRef(), ]; final schema = - schemas[refs.firstWhereOrNull((ref) => ref?.isNotEmpty == true)]; + schemas[refs.firstWhereOrNull((ref) => ref?.isNotEmpty == true)]; if (schema == null) { return false; @@ -576,7 +574,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return parameter.items!.ref.getRef().asEnum(); } return _mapParameterName( - parameter.items!.ref.getRef(), format, modelPostfix) + parameter.items!.ref.getRef(), format, modelPostfix) .asList(); } else if (parameter.schema?.items?.hasRef == true) { if (_isEnumRefParameter(parameter, root)) { @@ -659,33 +657,27 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .whereNotNull(); final additionalHeaders = - options.additionalHeaders.map((e) => - SwaggerRequestParameter( - inParameter: 'header', - name: e, - type: 'String', - )); + options.additionalHeaders.map((e) => SwaggerRequestParameter( + inParameter: 'header', + name: e, + type: 'String', + )); final parameters = [ ...swaggerRequest.parameters, ...swaggerPath.parameters, ...securityParameters, ...additionalHeaders, - ].map((par) => - definedParameters[par.ref - .split('/') - .last] ?? par).toList(); + ].map((par) => definedParameters[par.ref.split('/').last] ?? par).toList(); final result = parameters .where((swaggerParameter) => - ignoreHeaders ? swaggerParameter.inParameter != kHeader : true) + ignoreHeaders ? swaggerParameter.inParameter != kHeader : true) .where((swaggerParameter) => swaggerParameter.inParameter != kCookie) .where((swaggerParameter) => swaggerParameter.inParameter.isNotEmpty) .map( - (swaggerParameter) => - Parameter( - (p) => - p + (swaggerParameter) => Parameter( + (p) => p ..name = swaggerParameter.name.asParameterName() ..named = true ..required = swaggerParameter.isRequired && @@ -708,7 +700,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ) ..defaultTo = _getHeaderDefaultValue(swaggerParameter), ), - ) + ) .toList(); final requestBody = swaggerRequest.requestBody; @@ -726,8 +718,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (requestBody.content?.schema?.ref.isNotEmpty == true) { result.add( Parameter( - (p) => - p + (p) => p ..name = kBody ..named = true ..required = true @@ -747,8 +738,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (schema?.properties.isEmpty == true) { result.add( Parameter( - (p) => - p + (p) => p ..name = 'file' ..named = true ..required = true @@ -769,11 +759,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { value.type == 'file') { final isRequired = schema!.required.contains(key); final typeName = - _mapParameterName(value.type, value.format, modelPostfix); + _mapParameterName(value.type, value.format, modelPostfix); result.add( Parameter( - (p) => - p + (p) => p ..name = key ..named = true ..required = isRequired @@ -791,12 +780,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ); } else { final typeName = - _mapParameterName(value.type, value.format, modelPostfix); + _mapParameterName(value.type, value.format, modelPostfix); result.add( Parameter( - (p) => - p + (p) => p ..name = SwaggerModelsGenerator.getValidatedParameterName(key) ..named = true ..required = schema!.required.contains(key) @@ -844,7 +832,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { typeName = kObject.pascalCase; } else if (schema.items?.type.isNotEmpty == true) { typeName = _mapParameterName(schema.items!.type, schema.items!.format, - options.modelPostfix) + options.modelPostfix) .asList(); } else { typeName = _getRequestBodyTypeName( @@ -858,8 +846,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { result.add( Parameter( - (p) => - p + (p) => p ..name = kBody ..named = true ..required = true @@ -895,7 +882,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { schemas.addAll(root.definitions); final neededSchemaKey = - schemas.keys.firstWhereOrNull((key) => key.getRef() == ref.getRef()); + schemas.keys.firstWhereOrNull((key) => key.getRef() == ref.getRef()); if (neededSchemaKey == null) { return false; @@ -963,8 +950,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { Code? _getHeaderDefaultValue(SwaggerRequestParameter swaggerParameter) { final overridenValue = options.defaultHeaderValuesMap.firstWhereOrNull( - (map) => - map.headerName.toLowerCase() == + (map) => + map.headerName.toLowerCase() == swaggerParameter.name.toLowerCase()); if (overridenValue != null) { @@ -994,8 +981,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }) { return responses.entries .firstWhereOrNull((responseEntry) => - successResponseCodes.contains(responseEntry.key) || - successDescriptions.contains(responseEntry.value.description)) + successResponseCodes.contains(responseEntry.key) || + successDescriptions.contains(responseEntry.value.description)) ?.value; } @@ -1007,8 +994,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return '${methodName.pascalCase}\$$kResponse$modelPostfix'; } - String? _getReturnTypeFromType(SwaggerResponse swaggerResponse, - String modelPostfix) { + String? _getReturnTypeFromType( + SwaggerResponse swaggerResponse, String modelPostfix) { final responseType = swaggerResponse.schema?.type ?? ''; if (responseType.isEmpty) { return null; @@ -1034,8 +1021,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return kBasicTypesMap[responseType] ?? responseType + modelPostfix; } - String? _getReturnTypeFromSchema(SwaggerResponse swaggerResponse, - String modelPostfix, SwaggerRoot root) { + String? _getReturnTypeFromSchema( + SwaggerResponse swaggerResponse, String modelPostfix, SwaggerRoot root) { final listRef = swaggerResponse.schema?.items?.ref ?? ''; if (listRef.isNotEmpty) { @@ -1085,8 +1072,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return results; } - String? _getReturnTypeFromOriginalRef(SwaggerResponse swaggerResponse, - String modelPostfix) { + String? _getReturnTypeFromOriginalRef( + SwaggerResponse swaggerResponse, String modelPostfix) { if (swaggerResponse.schema?.hasOriginalRef == true) { return swaggerResponse.schema!.originalRef + modelPostfix; } @@ -1242,9 +1229,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return ''; } - String getChopperClientContent(String className, - String host, - String basePath,) { + String getChopperClientContent( + String className, + String host, + String basePath, + ) { final baseUrlString = options.withBaseUrl ? "baseUrl: baseUrl ?? Uri.parse('http://$host$basePath')" : 'baseUrl: baseUrl'; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 34e1f047..40a962a1 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -8,7 +8,7 @@ part of 'generator_options.dart'; GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( withBaseUrl: json['with_base_url'] as bool? ?? true, - addBasePathToRequests: json['add_base_path_to_requests'] as bool? ?? true, + addBasePathToRequests: json['add_base_path_to_requests'] as bool? ?? false, withConverter: json['with_converter'] as bool? ?? true, ignoreHeaders: json['ignore_headers'] as bool? ?? false, separateModels: json['separate_models'] as bool? ?? false, From f064936caedd38bf8caaba5423556f489b637a16 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 14:20:09 +0300 Subject: [PATCH 02/67] formatted code --- lib/src/models/generator_options.g2.dart | 3 ++- lib/swagger_dart_code_generator.dart | 8 ++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 40a962a1..6050b4a8 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -8,7 +8,8 @@ part of 'generator_options.dart'; GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( withBaseUrl: json['with_base_url'] as bool? ?? true, - addBasePathToRequests: json['add_base_path_to_requests'] as bool? ?? false, + addBasePathToRequests: + json['add_base_path_to_requests'] as bool? ?? false, withConverter: json['with_converter'] as bool? ?? true, ignoreHeaders: json['ignore_headers'] as bool? ?? false, separateModels: json['separate_models'] as bool? ?? false, diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 46830e19..ed000cff 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -292,12 +292,8 @@ class SwaggerDartCodeGenerator implements Builder { } } - String _generateFileContent( - String imports, - String requests, - String models, - String customDecoder, - String dateToJson) { + String _generateFileContent(String imports, String requests, String models, + String customDecoder, String dateToJson) { final result = """ $imports From 352d09f9736ce26929a12ca9a22ceb8b9141a9c4 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 14:21:10 +0300 Subject: [PATCH 03/67] updated SDK --- pubspec.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pubspec.yaml b/pubspec.yaml index b5a52160..645787e3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.6 +version: 2.11.6+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 @@ -19,7 +19,7 @@ description: Have you been turned into a problem with writing code for Http functionality you have been looking for. environment: - sdk: ">=2.12.0 <3.0.0" + sdk: ">=2.12.0 <4.0.0" dependencies: build: ^2.2.1 From 861dfac13a559d50901bff93f3766d8a31f42845 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 14:22:37 +0300 Subject: [PATCH 04/67] Updated SDK and version --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5edcb1bc..ef523c45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.11.7 + +* Updated SDK version + # 2.11.6 * Fixed generation of anyOf ref properties ([#613](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/613)) diff --git a/pubspec.yaml b/pubspec.yaml index 645787e3..bc1e0565 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.6+1 +version: 2.11.7 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 d320f1239de14a07862d97be77d3a900935bfa88 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 15:47:01 +0300 Subject: [PATCH 05/67] Fixed generation of lists of classes --- 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 14e4bcbb..530f3ac9 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -350,6 +350,10 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return '${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}$modelPostfix'; } + if(parameter.items?.properties.isNotEmpty == true) { + return 'List<${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}\$Item$modelPostfix>'; + } + if (parameter.hasRef) { return parameter.ref.split('/').last.pascalCase; } From fbda2491aad44c53cbc6f4c614476635c870ddbd Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 16:53:51 +0300 Subject: [PATCH 06/67] Fixed generation $Items classes --- lib/src/code_generators/swagger_models_generator.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 530f3ac9..faee6210 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -173,7 +173,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (items != null && items.properties.isNotEmpty) { propSchema.type = 'object'; - result['$innerClassName\$Item'] = propSchema; + result['$innerClassName\$Item'] = items; } }); @@ -350,7 +350,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return '${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}$modelPostfix'; } - if(parameter.items?.properties.isNotEmpty == true) { + if (parameter.items?.properties.isNotEmpty == true) { return 'List<${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}\$Item$modelPostfix>'; } From 1ade0c7b9d1f06407ea4e02308f8d8e7a01b162a Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 18:01:41 +0300 Subject: [PATCH 07/67] Updated pubspec and changelog --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef523c45..251639f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.11.8 + +* Fixed generation of fields of some models + # 2.11.7 * Updated SDK version diff --git a/pubspec.yaml b/pubspec.yaml index bc1e0565..b8685b46 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.7 +version: 2.11.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 fe41f12a8cb96aaccaf3e44e47cc273fa7d9abb1 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 9 Jun 2023 16:22:54 +0300 Subject: [PATCH 08/67] Fixed #524 --- lib/src/code_generators/swagger_models_generator.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index faee6210..fb026ae1 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -631,7 +631,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final allOf = prop.allOf; String typeName; - if (allOf.length != 1) { + if (allOf + .where((element) => + element.ref.isNotEmpty || element.properties.isNotEmpty) + .length > + 1) { typeName = kDynamic; } else { var className = allOf.first.ref.getRef(); From 173d9aad8fe350f2a9640f9313fc23310be05db8 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 23 Jun 2023 15:33:21 +0300 Subject: [PATCH 09/67] Fixed #598 Generation of query enum parameters --- .../swagger_enums_generator.dart | 12 ++++-- .../swagger_requests_generator.dart | 7 ++- .../requests/swagger_request_parameter.dart | 33 ++++++++------ .../swagger_request_parameter.g2.dart | 43 ++++++++++--------- 4 files changed, 56 insertions(+), 39 deletions(-) diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index b7a07f31..50cdac2d 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -186,9 +186,15 @@ ${allEnums.map((e) => e.toString()).join('\n')} name = getValidatedClassName(name); - final enumValues = swaggerRequestParameter.schema?.enumValues ?? - swaggerRequestParameter.items?.enumValues ?? - []; + List enumValues; + + if (swaggerRequestParameter.enumValues.isNotEmpty) { + enumValues = swaggerRequestParameter.enumValues; + } else { + enumValues = swaggerRequestParameter.schema?.enumValues ?? + swaggerRequestParameter.items?.enumValues ?? + []; + } final enumNames = swaggerRequestParameter.schema?.enumNames ?? []; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 54034d22..a9786dd3 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -556,10 +556,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }) { final format = parameter.schema?.format ?? ''; - if (parameter.inParameter == kHeader) { - return _mapParameterName(kString, format, ''); - } else if (parameter.items?.enumValues.isNotEmpty == true || - parameter.schema?.enumValues.isNotEmpty == true) { + if (parameter.items?.enumValues.isNotEmpty == true || + parameter.schema?.enumValues.isNotEmpty == true || + parameter.enumValues.isNotEmpty) { if (definedParameters.containsValue(parameter)) { return getValidatedClassName(parameter.name).asEnum(); } diff --git a/lib/src/swagger_models/requests/swagger_request_parameter.dart b/lib/src/swagger_models/requests/swagger_request_parameter.dart index 4cf032c1..f0c50d59 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.dart @@ -7,18 +7,20 @@ part 'swagger_request_parameter.g2.dart'; @JsonSerializable() class SwaggerRequestParameter { - SwaggerRequestParameter( - {this.inParameter = '', - this.name = '', - this.description = '', - this.isRequired = false, - this.type = '', - this.item, - this.collectionFormat = '', - this.items, - this.schema, - this.ref = '', - this.key = ''}); + SwaggerRequestParameter({ + this.inParameter = '', + this.name = '', + this.description = '', + this.isRequired = false, + this.type = '', + this.item, + this.collectionFormat = '', + this.items, + this.schema, + this.ref = '', + this.key = '', + this.enumValuesObj = const [], + }); @JsonKey(name: 'in', defaultValue: '') String inParameter; @@ -41,6 +43,13 @@ class SwaggerRequestParameter { @JsonKey(name: 'item') ParameterItem? item; + @JsonKey(name: 'enum', defaultValue: []) + List enumValuesObj; + + List get enumValues { + return enumValuesObj.map((e) => e.toString()).toList(); + } + @JsonKey(name: 'collectionFormat', defaultValue: '') String collectionFormat; diff --git a/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart b/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart index fcb8b2e9..ba9e136e 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart @@ -7,26 +7,27 @@ part of 'swagger_request_parameter.dart'; // ************************************************************************** SwaggerRequestParameter _$SwaggerRequestParameterFromJson( - Map json) { - return SwaggerRequestParameter( - inParameter: json['in'] as String? ?? '', - name: json['name'] as String? ?? '', - description: json['description'] as String? ?? '', - isRequired: json['required'] as bool? ?? false, - type: json['type'] as String? ?? '', - item: json['item'] == null - ? null - : ParameterItem.fromJson(json['item'] as Map), - collectionFormat: json['collectionFormat'] as String? ?? '', - items: json['items'] == null - ? null - : SwaggerRequestItems.fromJson(json['items'] as Map), - schema: json['schema'] == null - ? null - : SwaggerSchema.fromJson(json['schema'] as Map), - ref: json[r'$ref'] as String? ?? '', - ); -} + Map json) => + SwaggerRequestParameter( + inParameter: json['in'] as String? ?? '', + name: json['name'] as String? ?? '', + description: json['description'] as String? ?? '', + isRequired: json['required'] as bool? ?? false, + type: json['type'] as String? ?? '', + item: json['item'] == null + ? null + : ParameterItem.fromJson(json['item'] as Map), + collectionFormat: json['collectionFormat'] as String? ?? '', + items: json['items'] == null + ? null + : SwaggerRequestItems.fromJson(json['items'] as Map), + schema: json['schema'] == null + ? null + : SwaggerSchema.fromJson(json['schema'] as Map), + ref: json[r'$ref'] as String? ?? '', + key: json['key'] as String? ?? '', + enumValuesObj: json['enum'] as List? ?? [], + ); Map _$SwaggerRequestParameterToJson( SwaggerRequestParameter instance) => @@ -38,7 +39,9 @@ Map _$SwaggerRequestParameterToJson( r'$ref': instance.ref, 'type': instance.type, 'item': instance.item, + 'enum': instance.enumValuesObj, 'collectionFormat': instance.collectionFormat, 'schema': instance.schema, 'items': instance.items, + 'key': instance.key, }; From 16b5e3fcb0f37f0f3e87926d7aba8a4f230b31e2 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 23 Jun 2023 15:37:33 +0300 Subject: [PATCH 10/67] Fixed conflicts --- 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 c6f69f29..7783b9aa 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -87,8 +87,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { )) ..optionalParameters.add(Parameter( (p) => p -<<<<<<< HEAD -======= ..named = true ..type = Reference('http.Client?') ..name = 'httpClient', @@ -96,7 +94,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..optionalParameters.add(Parameter( (p) => p ->>>>>>> master ..named = true ..type = Reference('Authenticator?') ..name = 'authenticator', From d1c7d2f2bda196e4c401b2d0f589e264d2f59ee8 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 5 Jul 2023 15:10:54 +0300 Subject: [PATCH 11/67] Fixed some issues in swaggers --- .../swagger_additions_generator.dart | 4 +-- .../swagger_enums_generator.dart | 13 +++++-- .../swagger_models_generator.dart | 4 +++ .../swagger_requests_generator.dart | 34 +++++++++++++++---- .../requests/swagger_request.g2.dart | 2 ++ lib/swagger_dart_code_generator.dart | 4 +-- 6 files changed, 48 insertions(+), 13 deletions(-) diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index eb5a4ed4..34bad4a1 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -69,15 +69,13 @@ import 'package:chopper/chopper.dart' as chopper;'''; final enumsExport = hasEnums ? "export '$swaggerFileName.enums.swagger.dart';" : ''; - if (hasModels && !separateModels) { - result.writeln(""" + result.writeln(""" // ignore_for_file: type=lint import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; ${options.overrideToString ? "import 'dart:convert';" : ''} """); - } if (hasModels && separateModels) { result.write("import '$swaggerFileName.models.swagger.dart';"); diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index 50cdac2d..acd0ae12 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -76,7 +76,7 @@ abstract class SwaggerEnumsGenerator extends SwaggerGeneratorBase { ...enumsFromRequestBodies, ]; - return result; + return result.unique((e) => e.name); } String generateFromMap( @@ -132,7 +132,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} definedParameters.forEach((key, swaggerRequestParameter) { final enumValues = swaggerRequestParameter.schema?.enumValues ?? swaggerRequestParameter.items?.enumValues ?? - []; + swaggerRequestParameter.enumValues; final enumNames = swaggerRequestParameter.schema?.enumNames ?? []; @@ -391,3 +391,12 @@ ${allEnums.map((e) => e.toString()).join('\n')} return generateEnumsContentFromModelProperties(properties, className); } } + +extension Unique on List { + List unique([Id Function(E element)? id, bool inplace = true]) { + final ids = {}; + var list = inplace ? this : List.from(this); + list.retainWhere((x) => ids.add(id != null ? id(x) : x as Id)); + return list; + } +} diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index fb026ae1..b4a7760c 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -554,6 +554,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { + if(typeName.isEmpty) { + return kObject.pascalCase.makeNullable(); + } + if (options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey) || prop.isNullable == true) { diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 7783b9aa..580e583f 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -92,8 +92,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..name = 'httpClient', )) ..optionalParameters.add(Parameter( - (p) => - p + (p) => p ..named = true ..type = Reference('Authenticator?') ..name = 'authenticator', @@ -331,7 +330,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (!response.startsWith('$kMap<')) { final neededResponse = response.removeListOrStream(); - if (!kBasicTypes.contains(neededResponse)) { + if (!kBasicTypes.contains(neededResponse) && + neededResponse != kDynamic) { results.add(getValidatedClassName(neededResponse)); } } @@ -363,6 +363,13 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } } + if (p.annotations.first.code.toString().contains('symbol=Header')) { + if (p.type?.symbol?.startsWith('List<') == true) { + return p.copyWith(type: Reference('Iterable?')); + } + return p.copyWith(type: Reference('String?')); + } + if (p.type!.symbol!.startsWith('List')) { final listType = p.type!.symbol!.removeListOrStream(); @@ -400,7 +407,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..name = method.name ..returns = method.returns ..body = _generatePublicMethodCode( - parameters, + method.optionalParameters, method.name!, allModels, ), @@ -417,6 +424,16 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return '${p.name} : ${p.name}?.value?.toString()'; } + if (p.annotations.firstOrNull?.code + .toString() + .contains('symbol=Header') == + true) { + if (p.type?.symbol?.startsWith('List<') == true) { + return '${p.name} : ${p.name}?.map((e) => e.toString())'; + } + return '${p.name} : ${p.name}?.toString()'; + } + if (p.type!.symbol!.startsWith('List e.value == parameter) + ?.key ?? + ''; + final b = 0; + return getValidatedClassName(neededKey).asEnum(); } return _getEnumParameterTypeName( @@ -635,7 +657,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return 'List?'; } - final result = kBasicTypesMap[name] ?? name.pascalCase + modelPostfix; + final result = kBasicTypesMap[name] ?? ''; if (result.isEmpty) { return kDynamic; diff --git a/lib/src/swagger_models/requests/swagger_request.g2.dart b/lib/src/swagger_models/requests/swagger_request.g2.dart index 0a930a3f..22955754 100644 --- a/lib/src/swagger_models/requests/swagger_request.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request.g2.dart @@ -63,6 +63,7 @@ Map _$RequestBodyToJson(RequestBody instance) => RequestContent _$RequestContentFromJson(Map json) => RequestContent( + isMultipart: json['isMultipart'] as bool?, schema: json['schema'] == null ? null : SwaggerSchema.fromJson(json['schema'] as Map), @@ -71,4 +72,5 @@ RequestContent _$RequestContentFromJson(Map json) => Map _$RequestContentToJson(RequestContent instance) => { 'schema': instance.schema, + 'isMultipart': instance.isMultipart, }; diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index ed000cff..32c0d9fa 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -223,10 +223,10 @@ class SwaggerDartCodeGenerator implements Builder { allEnums, options, ); - + final imports = codeGenerator.generateImportsContent( fileNameWithoutExtension, - models.isNotEmpty, + models.contains('@JsonSerializable'), options.buildOnlyModels, enums.isNotEmpty, options.separateModels, From 6ae1b7d819c8b1bef4f86a0983ee8bd51e707fe1 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 5 Jul 2023 15:12:47 +0300 Subject: [PATCH 12/67] Updated changelog and pubspec --- CHANGELOG.md | 1 + lib/src/code_generators/swagger_requests_generator.dart | 1 - pubspec.yaml | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fec2e75..af45a379 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ * Bump `package:http` to `^1.0.0` * Bump minimum dart version to `^3.0.0` * Fixed #625 generation of query enum parameters +* Fixed some issues # 2.11.8 diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 580e583f..30b27809 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -588,7 +588,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .firstWhereOrNull((e) => e.value == parameter) ?.key ?? ''; - final b = 0; return getValidatedClassName(neededKey).asEnum(); } diff --git a/pubspec.yaml b/pubspec.yaml index 060825a7..d76ea744 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.8 +version: 2.11.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 ff4d14ead8bc8c4b0e416160227e100f4b6d8551 Mon Sep 17 00:00:00 2001 From: Romain Date: Fri, 8 Sep 2023 11:13:31 +0200 Subject: [PATCH 13/67] Fix #583, #637, #619 and update readme (#638) * fix #583 and update readme * fix #637 * fix #619 --- README.md | 1 + lib/src/code_generators/enum_model.dart | 10 ++++++ .../swagger_models_generator.dart | 32 +++++++++++++------ .../swagger_requests_generator.dart | 15 +++++---- 4 files changed, 42 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index bbaebec5..dc8e25d9 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ targets: | `override_equals_and_hashcode` | `-` | `true` | If need to decrease app size - you can disable generation of `hashcode` and `Equals` method. | | `overriden_models` | `-` | `false` | List of manually written models that will replace the generated one. These models will not be generated. | | `use_path_for_request_names` | `true` | `false` | Can be false only if all requests has unique `operationId`. It gives readable names for requests. | +| `addBasePathToRequests` | `true` | `false` | Add swagger base path to all request path. | It's important to remember that, by default, [build](https://github.com/dart-lang/build) will follow [Dart's package layout conventions](https://dart.dev/tools/pub/package-layout), meaning that only some folders will be considered to parse the input files. So, if you want to reference files from a folder other than `lib/`, make sure you've included it on `sources`: diff --git a/lib/src/code_generators/enum_model.dart b/lib/src/code_generators/enum_model.dart index 51901661..4ce5f070 100644 --- a/lib/src/code_generators/enum_model.dart +++ b/lib/src/code_generators/enum_model.dart @@ -116,6 +116,16 @@ enums.$name ${name.camelCase}FromJson( return enums.$name.values.firstWhereOrNull((e) => e.value == ${name.camelCase}) ?? defaultValue ?? enums.$name.swaggerGeneratedUnknown; } +enums.$name? ${name.camelCase}NullableFromJson( + Object? ${name.camelCase}, + [enums.$name? defaultValue,] + ) { + if(${name.camelCase} == null){ + return null; + } + return enums.$name.values.firstWhereOrNull((e) => e.value == ${name.camelCase}) ?? defaultValue; +} + List<$type> ${name.camelCase}ListToJson( List? ${name.camelCase}) { diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index b4a7760c..c0b02c3b 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -424,6 +424,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { typeName = kDynamic; } + final propertyKey = propertyName.replaceAll('\$', '\\\$'); + final unknownEnumValue = generateEnumValue( allEnumNames: allEnumNames, allEnumListNames: allEnumListNames, @@ -431,6 +433,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { typeName: typeName.toString(), defaultValue: prop.defaultValue, isList: false, + isNullable: isNullable(typeName, [], propertyKey, prop), ); final dateToJsonValue = generateToJsonForDate(prop); @@ -441,8 +444,6 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { typeName += '?'; } - final propertyKey = propertyName.replaceAll('\$', '\\\$'); - final jsonKeyContent = "@JsonKey(name: '$propertyKey'$includeIfNullString$dateToJsonValue${unknownEnumValue.jsonKey})\n"; return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; @@ -455,6 +456,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { required String typeName, required dynamic defaultValue, required bool isList, + required bool isNullable, String className = '', }) { final validatedTypeName = getValidatedClassName(typeName); @@ -485,7 +487,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { : 'ListFromJson'; toJsonSuffix = 'ListToJson'; } else { - fromJsonSuffix = 'FromJson'; + fromJsonSuffix = isNullable ? 'NullableFromJson' : 'FromJson'; toJsonSuffix = 'ToJson'; } final fromJsonFunction = '$fromJsonPrefix$fromJsonSuffix'; @@ -517,7 +519,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { '$validatedTypeName.${defaultValueCamelCase.substring(0, defaultValueCamelCase.indexOf('('))}'; } - if (options.classesWithNullabeLists.contains(className) && isList) { + if ((options.classesWithNullabeLists.contains(className) && isList) || + isNullable) { returnType = '$returnType?'; } @@ -547,6 +550,13 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr return ''; } + bool isNullable(String className, Iterable requiredProperties, + String propertyKey, SwaggerSchema prop) { + return options.nullableModels.contains(className) || + !requiredProperties.contains(propertyKey) || + prop.isNullable == true; + } + String nullable( String typeName, String className, @@ -554,13 +564,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { - if(typeName.isEmpty) { + if (typeName.isEmpty) { return kObject.pascalCase.makeNullable(); } - - if (options.nullableModels.contains(className) || - !requiredProperties.contains(propertyKey) || - prop.isNullable == true) { + + if (isNullable(className, requiredProperties, propertyKey, prop)) { return typeName.makeNullable(); } return typeName; @@ -605,6 +613,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: typeName, defaultValue: prop.defaultValue, isList: false, + isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); final dateToJsonValue = generateToJsonForDate(prop); @@ -664,6 +673,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: typeName, defaultValue: prop.defaultValue, isList: false, + isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); final jsonKeyContent = @@ -721,6 +731,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr defaultValue: prop.defaultValue, className: className, isList: false, + isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); if (allEnumListNames.contains(typeName)) { @@ -770,6 +781,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: enumName, defaultValue: prop.defaultValue, isList: false, + isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); final includeIfNullString = generateIncludeIfNullString(); @@ -900,6 +912,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: typeName, defaultValue: prop.defaultValue, isList: true, + isNullable: false, ); final includeIfNullString = generateIncludeIfNullString(); @@ -970,6 +983,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: typeName, defaultValue: prop.defaultValue, isList: false, + isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); final dateToJsonValue = generateToJsonForDate(prop); diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 30b27809..d947c060 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -143,10 +143,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return; } - if (options.addBasePathToRequests) { - path = '${swaggerRoot.basePath}$path'; - } - final methodName = _getRequestMethodName( requestType: requestType, swaggerRequest: swaggerRequest, @@ -197,6 +193,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .any((p0) => p0.call([]).toString().contains('symbol=Part')); }); + var annotationPath = path; + if (options.addBasePathToRequests) { + annotationPath = '${swaggerRoot.basePath}$path'; + } + final method = Method((m) => m ..optionalParameters.addAll(parameters) ..docs.add(_getCommentsForMethod( @@ -206,7 +207,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { )) ..name = methodName ..annotations.addAll(_getMethodAnnotation( - requestType, path, hasOptionalBody, isMultipart)) + requestType, annotationPath, hasOptionalBody, isMultipart)) ..returns = Reference(returns)); final allModels = _getAllMethodModels( @@ -1036,9 +1037,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final arrayType = [itemsRef, itemsOriginalRef, itemsType, kObject] .firstWhere((element) => element?.isNotEmpty == true)!; - final mappedArrayType = kBasicTypesMap[arrayType] ?? arrayType; + final mappedArrayType = kBasicTypesMap[arrayType]; - if (mappedArrayType.isEmpty) { + if (mappedArrayType == null) { return null; } From 290deb0517dae239cd49591b7a75baf58aeff1de Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 11:03:53 +0300 Subject: [PATCH 14/67] Fixed generation of some fields --- lib/src/code_generators/swagger_models_generator.dart | 2 +- lib/src/code_generators/swagger_requests_generator.dart | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 8e8c686c..314624df 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1345,7 +1345,7 @@ String toString() => jsonEncode(this); final generatedClass = ''' @JsonSerializable(explicitToJson: true $createToJson) class $validatedClassName{ -\t$validatedClassName($generatedConstructorProperties);\n +\tconst $validatedClassName($generatedConstructorProperties);\n \t$fromJson\n \t$toJson\n $generatedProperties diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index f66a316d..83ff8e5d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -1204,6 +1204,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final contentSchemaType = content.schema?.type ?? ''; if (contentSchemaType.isNotEmpty == true) { + if (contentSchemaType == 'string' && + content.schema?.format == 'date-time') { + return 'DateTime'; + } return kBasicTypesMap[contentSchemaType]; } From d3a77ebc6d39c0239d17d5788ceffaeae063e8b5 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 11:07:24 +0300 Subject: [PATCH 15/67] Removed test --- .../models_generator_test.dart | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 41d2c500..edae40e5 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -302,26 +302,6 @@ void main() { expect(result, contains(jsonKeyExpectedResult)); expect(result, contains(fieldExpectedResult)); }); - - test('Should add fromJson and toJson by ref', () { - final map = SwaggerSchema(schema: SwaggerSchema(ref: 'Pet')); - const propertyName = 'dog'; - const className = 'Animals'; - const propertyKey = 'Dog'; - - final result = generator.generatePropertyContentBySchema( - map, - propertyName, - propertyKey, - className, - ['enums.Pet'], - [], - {}, - [], - ); - - expect(result, contains('toJson: petToJson, fromJson: petFromJson')); - }); }); group('generatePropertiesContent', () { From 8283674ea3223015da0e86dc05a4bfda4f6f2218 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 11:39:49 +0300 Subject: [PATCH 16/67] Fixed classes named List --- example/lib/main.dart | 21 --------------------- lib/src/code_generators/constants.dart | 1 + lib/src/code_generators/enum_model.dart | 2 +- 3 files changed, 2 insertions(+), 22 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index ad3bc568..e69de29b 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,21 +0,0 @@ -import 'package:example/swagger_generated_code/pet_service_yaml.swagger.dart'; - -void main() async { - final petsApi = PetServiceYaml.create(); - - final postResult = await petsApi.petPost( - body: Pet( - name: 'Vovanella', - photoUrls: [ - 'https://i.ytimg.com/vi/hO6G8jxV-YU/maxresdefault.jpg', - 'https://i.ytimg.com/vi/5u3iv8AT8G8/maxresdefault.jpg' - ], - status: PetStatus.available, - category: Category(), - ), - ); - - final pet = Pet.fromJson(postResult.body as Map); - - print('Created pet id: ${pet.id}'); -} diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 701a4086..35690b25 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -12,6 +12,7 @@ const List kKeyClasses = [ 'Body', 'Method', 'Uri', + 'List', ]; const kBasicTypes = [ diff --git a/lib/src/code_generators/enum_model.dart b/lib/src/code_generators/enum_model.dart index 127e94ea..84c35094 100644 --- a/lib/src/code_generators/enum_model.dart +++ b/lib/src/code_generators/enum_model.dart @@ -105,7 +105,7 @@ const $name(this.value); String enumParse = caseSensitive ? 'return enums.$name.values.firstWhereOrNull((e) => e.value == ${name.camelCase}) ?? defaultValue ?? enums.$name.swaggerGeneratedUnknown' - : 'return enums.$name.values.firstWhereOrNull((e) => e.value.toString().toLowerCase() == ${name.camelCase}?.toString()?.toLowerCase()) ?? defaultValue ?? enums.$name.swaggerGeneratedUnknown'; + : 'return enums.$name.values.firstWhereOrNull((e) => e.value.toString().toLowerCase() == ${name.camelCase}?.toString().toLowerCase()) ?? defaultValue ?? enums.$name.swaggerGeneratedUnknown'; return ''' $type? ${name.camelCase}ToJson(enums.$name? ${name.camelCase}) { From a71a9e9225c0ceca9d91a54c55a68c9f3d96a3ef Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 11:54:51 +0300 Subject: [PATCH 17/67] Fixed generation of query parameters with ref default type --- .../code_generators/swagger_requests_generator.dart | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 83ff8e5d..59faf38c 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -632,6 +632,17 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (parameter.schema!.items != null || parameter.schema!.type == kArray) { return (parameter.schema!.ref.getRef() + modelPostfix).asList(); } + + final ref = parameter.schema?.ref; + + if (ref != null) { + final neededSchema = root.allSchemas[ref.getUnformattedRef()]; + + if (kBasicTypesMap.containsKey(neededSchema?.type)) { + return kBasicTypesMap[neededSchema?.type]!; + } + } + return (parameter.schema!.ref.getRef() + modelPostfix); } else if (parameter.schema?.type == kArray && parameter.schema?.items?.type.isNotEmpty == true) { From d99e4f9a3cb3d00253eb67073a144f512c95347e Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 13:05:52 +0300 Subject: [PATCH 18/67] Fixed generation of DateTime parameters --- lib/src/code_generators/constants.dart | 3 +++ lib/src/code_generators/swagger_requests_generator.dart | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 35690b25..3b76d788 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -58,6 +58,7 @@ const kPath = 'path'; const kOptionalBody = 'optionalBody'; const kFormData = 'formData'; const kMultipart = 'multipart'; +const kDateTimeFormat = 'date-time'; const kDefaultBodyParameter = 'Object'; const kField = 'Field'; @@ -90,6 +91,8 @@ const kBody = 'body'; const kPartFile = 'partFile'; const kPart = 'part'; +const kDateTimeType = 'DateTime'; + const kDynamic = 'dynamic'; const supportedRequestTypes = ['get', 'post', 'put', 'delete', 'head', 'patch']; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 59faf38c..aaa502be 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -657,6 +657,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } if (parameter.schema?.type.isNotEmpty == true) { + if (parameter.schema?.format == kDateTimeFormat) { + return kDateTimeType; + } + return _mapParameterName(parameter.schema!.type, format, modelPostfix); } @@ -1216,8 +1220,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final contentSchemaType = content.schema?.type ?? ''; if (contentSchemaType.isNotEmpty == true) { if (contentSchemaType == 'string' && - content.schema?.format == 'date-time') { - return 'DateTime'; + content.schema?.format == kDateTimeFormat) { + return kDateTimeType; } return kBasicTypesMap[contentSchemaType]; } From e2fe57f25bd576c30c1b8ed18c2adc9dc57287a8 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 13:25:24 +0300 Subject: [PATCH 19/67] Fixed generation of responses in some cases --- .../swagger_requests_generator.dart | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index aaa502be..995cdb69 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -164,6 +164,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { responses: swaggerRequest.responses, path: path, methodName: methodName, + method: requestType, modelPostfix: options.modelPostfix, swaggerRoot: swaggerRoot, overridenResponses: options.responseOverrideValueMap @@ -1133,6 +1134,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required String modelPostfix, required SwaggerRoot swaggerRoot, required String requestName, + required String path, + required String method, }) { final content = swaggerResponse.content; @@ -1223,6 +1226,14 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { content.schema?.format == kDateTimeFormat) { return kDateTimeType; } + + if (content.schema?.properties.isNotEmpty == true) { + final pathText = path.split('/').map((e) => e.pascalCase).join(); + final requestText = method.pascalCase; + + return '$pathText$requestText\$Response'; + } + return kBasicTypesMap[contentSchemaType]; } @@ -1240,6 +1251,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required String methodName, required String modelPostfix, required SwaggerRoot swaggerRoot, + required String method, }) { if (overridenResponses.containsKey(path)) { return overridenResponses[path]!.overriddenValue; @@ -1270,6 +1282,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { modelPostfix: modelPostfix, swaggerRoot: swaggerRoot, requestName: methodName, + path: path, + method: method, ) ?? ''; From 1b2451521a710f43fdc7b67006b7bd3e2649244b Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 13:40:24 +0300 Subject: [PATCH 20/67] Some fixes --- lib/src/code_generators/swagger_models_generator.dart | 2 +- lib/src/code_generators/swagger_requests_generator.dart | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 314624df..c6960a6f 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -214,7 +214,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } final responses = request.responses; - final neededResponse = responses['200']; + final neededResponse = responses['200'] ?? responses['201']; final neededSchema = neededResponse?.schema ?? neededResponse?.content?.schema; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 995cdb69..1dce023d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -1231,7 +1231,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final pathText = path.split('/').map((e) => e.pascalCase).join(); final requestText = method.pascalCase; - return '$pathText$requestText\$Response'; + return getValidatedClassName('$pathText$requestText\$Response'); } return kBasicTypesMap[contentSchemaType]; From 4bdd297f20facabe38caf62ba7c84f6e2d5013b6 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Sep 2023 13:41:57 +0300 Subject: [PATCH 21/67] 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 58ce30a6..3a781fb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.11.11 + +* Fixes some stuff related to generation DateTime, reponse types and parameters types + # 2.11.10 * Bump `package:http` to `^1.0.0` diff --git a/pubspec.yaml b/pubspec.yaml index d76ea744..9d47f8e5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.10 +version: 2.11.11 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 3e6c74566a8e12b71790a97d55f15b5468e507a0 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Sep 2023 16:37:00 +0300 Subject: [PATCH 22/67] Implemented not nullable fields --- lib/src/code_generators/enum_model.dart | 6 +- .../swagger_models_generator.dart | 66 ++++++++++++------- .../swagger_requests_generator.dart | 2 + lib/src/models/generator_options.dart | 4 ++ lib/src/models/generator_options.g2.dart | 2 + .../responses/swagger_schema.dart | 3 +- 6 files changed, 58 insertions(+), 25 deletions(-) diff --git a/lib/src/code_generators/enum_model.dart b/lib/src/code_generators/enum_model.dart index 84c35094..9107c8c6 100644 --- a/lib/src/code_generators/enum_model.dart +++ b/lib/src/code_generators/enum_model.dart @@ -108,10 +108,14 @@ const $name(this.value); : 'return enums.$name.values.firstWhereOrNull((e) => e.value.toString().toLowerCase() == ${name.camelCase}?.toString().toLowerCase()) ?? defaultValue ?? enums.$name.swaggerGeneratedUnknown'; return ''' -$type? ${name.camelCase}ToJson(enums.$name? ${name.camelCase}) { +$type? ${name.camelCase}NullableToJson(enums.$name? ${name.camelCase}) { return ${name.camelCase}?.value; } +$type? ${name.camelCase}ToJson(enums.$name ${name.camelCase}) { + return ${name.camelCase}.value; +} + enums.$name ${name.camelCase}FromJson( Object? ${name.camelCase}, [enums.$name? defaultValue,] diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index c6960a6f..1c77f832 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -442,8 +442,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final includeIfNullString = generateIncludeIfNullString(); - if (typeName != kDynamic) { - typeName += '?'; + if (typeName != kDynamic && (prop.isNullable || options.nullableFields)) { + typeName = typeName.makeNullable(); } final jsonKeyContent = @@ -494,7 +494,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } final fromJsonFunction = '$fromJsonPrefix$fromJsonSuffix'; jsonKey = - ', toJson: $enumNameCamelCase$toJsonSuffix, fromJson: $fromJsonFunction, $defaultValueSuffix'; + ', toJson: $enumNameCamelCase${isNullable && !isList ? 'Nullable$toJsonSuffix' : toJsonSuffix}, fromJson: $fromJsonFunction, $defaultValueSuffix'; if (defaultValue != null) { var returnType = ''; @@ -552,10 +552,13 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr return ''; } - bool isNullable(String className, Iterable requiredProperties, - String propertyKey, SwaggerSchema prop) { + bool isNullable( + String className, + Iterable requiredProperties, + String propertyKey, + SwaggerSchema prop, + ) { return options.nullableModels.contains(className) || - !requiredProperties.contains(propertyKey) || prop.isNullable == true; } @@ -623,8 +626,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + if (prop.isNullable || options.nullableFields) { + typeName = + nullable(typeName, className, requiredProperties, propertyKey, prop); + } return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } @@ -681,8 +686,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + if (prop.isNullable || options.nullableFields) { + typeName = + nullable(typeName, className, requiredProperties, propertyKey, prop); + } return '\t$jsonKeyContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; } @@ -725,6 +732,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName += options.modelPostfix; } + final isPropertyNullable = refSchema?.isNullable == true || + isNullable(className, requiredProperties, propertyKey, prop); + final unknownEnumValue = generateEnumValue( allEnumNames: allEnumNames, allEnumListNames: allEnumListNames, @@ -733,7 +743,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr defaultValue: prop.defaultValue, className: className, isList: false, - isNullable: isNullable(className, requiredProperties, propertyKey, prop), + isNullable: isPropertyNullable, ); if (allEnumListNames.contains(typeName)) { @@ -745,8 +755,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + if (prop.isNullable || options.nullableFields) { + typeName = + nullable(typeName, className, requiredProperties, propertyKey, prop); + } final propertySchema = allClasses[prop.ref.getUnformattedRef()]; @@ -789,8 +801,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final includeIfNullString = generateIncludeIfNullString(); var enumPropertyName = className.capitalize + key.capitalize; - enumPropertyName = nullable( - enumPropertyName, className, requiredProperties, propertyKey, prop); + + if (prop.isNullable || options.nullableFields) { + enumPropertyName = nullable( + enumPropertyName, className, requiredProperties, propertyKey, prop); + } return ''' @JsonKey(${unknownEnumValue.jsonKey.substring(2)}$includeIfNullString) @@ -937,8 +952,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - listPropertyName = nullable( - listPropertyName, className, requiredParameters, propertyKey, prop); + if (prop.isNullable || options.nullableFields) { + listPropertyName = nullable( + listPropertyName, className, requiredParameters, propertyKey, prop); + } return '$jsonKeyContent final $listPropertyName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } @@ -1006,8 +1023,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += ')\n'; } - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + if (prop.isNullable || options.nullableFields) { + typeName = + nullable(typeName, className, requiredProperties, propertyKey, prop); + } return '\t$jsonKeyContent final $typeName $propertyName;${unknownEnumValue.fromJson}'; } @@ -1242,7 +1261,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String generateConstructorPropertiesContent({ required String className, - required Map entityMap, + required Map entityMap, required List defaultValues, required List requiredProperties, required List allEnumNames, @@ -1263,8 +1282,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyNames.add(fieldName); - if (options.nullableModels.contains(className) || - !requiredProperties.contains(key)) { + final isNullableProperty = options.nullableModels.contains(className) || + options.nullableFields || + value.isNullable; + + if (isNullableProperty) { results += '\t\tthis.$fieldName,\n'; } else { results += '\t\t$kRequired this.$fieldName,\n'; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 1dce023d..e2c93e48 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -233,6 +233,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ) { final results = []; + response = response.replaceAll('?', ''); + ///Models from parameters for (var parameter in request.parameters) { final ref = parameter.anyRef; diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 4be5e95f..1487ffee 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -37,6 +37,7 @@ class GeneratorOptions { this.overridenModels = const [], this.generateToJsonFor = const [], this.multipartFileType = 'List', + this.nullableFields = false, }); /// Build options from a JSON map. @@ -49,6 +50,9 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool withBaseUrl; + @JsonKey(defaultValue: false) + final bool nullableFields; + @JsonKey(defaultValue: false) final bool addBasePathToRequests; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 6050b4a8..60843370 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -84,12 +84,14 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( .toList() ?? [], multipartFileType: json['multipart_file_type'] as String? ?? 'List', + nullableFields: json['nullable_fields'] as bool? ?? false, ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => { 'use_path_for_request_names': instance.usePathForRequestNames, 'with_base_url': instance.withBaseUrl, + 'nullable_fields': instance.nullableFields, 'add_base_path_to_requests': instance.addBasePathToRequests, 'page_width': instance.pageWidth, 'override_to_string': instance.overrideToString, diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 27085012..4f1c3ff9 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -105,9 +105,8 @@ class SwaggerSchema { ?.map((e) => e as String) .toList() ..isNullable = (json[kIsNullable] ?? - json[kIsNullable] ?? json[kNullable] ?? - false) as bool; + true) as bool; Map toJson() => { ..._$SwaggerSchemaToJson(this), From bc0c305f19ed5801966f5a35e7a510cfc9f2dd12 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Sep 2023 16:42:14 +0300 Subject: [PATCH 23/67] Fixed tests --- .../models_generator_test.dart | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index edae40e5..f105c09b 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -263,8 +263,8 @@ void main() { }); test('Should return validate constructor property', () { - final map = { - 'Animal': {'type': 'dog'} + final map = { + 'Animal': SwaggerSchema() }; const expectedResult = 'this.animal'; final result = generator.generateConstructorPropertiesContent( @@ -287,7 +287,7 @@ void main() { const className = 'Animals'; const propertyKey = 'Dog'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Dog')\n"; - const fieldExpectedResult = '\tfinal Pet? dog'; + const fieldExpectedResult = '\tfinal Pet dog'; final result = generator.generatePropertyContentBySchema( map, propertyName, @@ -312,7 +312,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -339,7 +339,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -364,7 +364,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -389,7 +389,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: '\\\$with')\n"; - const fieldExpectedResult = 'final Pet? \$with'; + const fieldExpectedResult = 'final Pet \$with'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -417,7 +417,7 @@ void main() { const jsonKeyExpectedResult = "@JsonKey(name: 'Dog', defaultValue: [])"; - const propertyExpectedResult = 'final List? dog'; + const propertyExpectedResult = 'final List dog'; final result = generator.generateListPropertyContent( propertyName, propertyKey, @@ -477,7 +477,7 @@ void main() { {}, ); - expect(result, contains('final List? dog;')); + expect(result, contains('final List dog;')); }); test('Should return List by ref', () { @@ -500,7 +500,7 @@ void main() { {}, ); - expect(result, contains('final List? dog;')); + expect(result, contains('final List dog;')); }); }); From 0ed916367a90127367796025bda78bc9ec17ba96 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 13 Oct 2023 11:43:30 +0300 Subject: [PATCH 24/67] fixed generation of some swaggers --- lib/src/code_generators/swagger_models_generator.dart | 11 ++++++++--- .../code_generators/swagger_requests_generator.dart | 4 +--- lib/src/swagger_models/responses/swagger_schema.dart | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 1c77f832..d7f3e909 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -494,7 +494,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } final fromJsonFunction = '$fromJsonPrefix$fromJsonSuffix'; jsonKey = - ', toJson: $enumNameCamelCase${isNullable && !isList ? 'Nullable$toJsonSuffix' : toJsonSuffix}, fromJson: $fromJsonFunction, $defaultValueSuffix'; + ', toJson: $enumNameCamelCase${isNullable && !isList ? 'Nullable$toJsonSuffix' : toJsonSuffix}, fromJson: $fromJsonFunction, $defaultValueSuffix'; if (defaultValue != null) { var returnType = ''; @@ -657,7 +657,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr .length > 1) { typeName = kDynamic; - } else { + } else if (allOf.first.ref.isNotEmpty) { var className = allOf.first.ref.getRef(); if (allEnumNames.contains(className)) { @@ -665,6 +665,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr } typeName = getValidatedClassName(className); + } else if (allOf.first.type.isNotEmpty && + kBasicTypesMap.containsKey(allOf.first.type)) { + typeName = kBasicTypesMap[allOf.first.type]!; + } else { + typeName = kDynamic; } if (basicTypesMap.containsKey(typeName)) { @@ -762,7 +767,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final propertySchema = allClasses[prop.ref.getUnformattedRef()]; - if (propertySchema?.isNullable == true) { + if (propertySchema?.isNullable == true || isPropertyNullable) { typeName = typeName.makeNullable(); } diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index e2c93e48..3aed2d1f 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -233,8 +233,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ) { final results = []; - response = response.replaceAll('?', ''); - ///Models from parameters for (var parameter in request.parameters) { final ref = parameter.anyRef; @@ -259,7 +257,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (!kBasicTypes.contains(itemsType) && schema?.items?.properties != null) { - final itemClassName = '$response\$Item'; + final itemClassName = '${response.replaceAll('?', '')}\$Item'; results.add(itemClassName); } diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 4f1c3ff9..579b8ad8 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -106,7 +106,7 @@ class SwaggerSchema { .toList() ..isNullable = (json[kIsNullable] ?? json[kNullable] ?? - true) as bool; + false) as bool; Map toJson() => { ..._$SwaggerSchemaToJson(this), From baec549bb9663c44346d999f480e09b3872986ba Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 13 Oct 2023 12:26:01 +0300 Subject: [PATCH 25/67] Added ability to return String values --- lib/src/code_generators/swagger_additions_generator.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index 73d18b5c..a14e25da 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -198,6 +198,10 @@ class \$JsonSerializableConverter extends chopper.JsonConverter { return chopper.Response(response.base, null, error: response.error); } + if(ResultType == String) { + return response.copyWith(); + } + final jsonRes = await super.convertResponse(response); return jsonRes.copyWith( body: \$jsonDecoder.decode(jsonRes.body) as ResultType); From 899833eaf3763fc8ac43c24e14bef178def178e7 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 13 Oct 2023 12:27:55 +0300 Subject: [PATCH 26/67] Returned main.dart content --- example/lib/main.dart | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/example/lib/main.dart b/example/lib/main.dart index e69de29b..ad3bc568 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -0,0 +1,21 @@ +import 'package:example/swagger_generated_code/pet_service_yaml.swagger.dart'; + +void main() async { + final petsApi = PetServiceYaml.create(); + + final postResult = await petsApi.petPost( + body: Pet( + name: 'Vovanella', + photoUrls: [ + 'https://i.ytimg.com/vi/hO6G8jxV-YU/maxresdefault.jpg', + 'https://i.ytimg.com/vi/5u3iv8AT8G8/maxresdefault.jpg' + ], + status: PetStatus.available, + category: Category(), + ), + ); + + final pet = Pet.fromJson(postResult.body as Map); + + print('Created pet id: ${pet.id}'); +} From 1eabeb0ed7492f1c22080f3a06fd171ab33e812d Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 13 Oct 2023 12:33:10 +0300 Subject: [PATCH 27/67] Updated pubspec and changelog --- CHANGELOG.md | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a781fb2..3359467f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 2.11.12 + +* Added generation of const constructors +* Added support of required not nullable properties ([#650](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/650)) +* Fixed generation of String responses in converter ([#631](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/631)) + # 2.11.11 * Fixes some stuff related to generation DateTime, reponse types and parameters types diff --git a/pubspec.yaml b/pubspec.yaml index 9d47f8e5..a620aa67 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.11 +version: 2.11.12 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 360b837a53cf3a6244328c44b4bd0e549157a5ec Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 12:28:47 +0300 Subject: [PATCH 28/67] Fixed generation of required and not required fields --- .../swagger_models_generator.dart | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index d7f3e909..ec8a8e44 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -415,6 +415,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { String propertyName, List allEnumNames, List allEnumListNames, + List requiredProperties, ) { var typeName = ''; @@ -446,6 +447,11 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { typeName = typeName.makeNullable(); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + typeName = typeName.makeNullable(); + } + final jsonKeyContent = "@JsonKey(name: '$propertyKey'$includeIfNullString$dateToJsonValue${unknownEnumValue.jsonKey})\n"; return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; @@ -631,6 +637,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr nullable(typeName, className, requiredProperties, propertyKey, prop); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + typeName = typeName.makeNullable(); + } + return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } @@ -696,6 +707,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr nullable(typeName, className, requiredProperties, propertyKey, prop); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + typeName = typeName.makeNullable(); + } + return '\t$jsonKeyContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; } @@ -765,6 +781,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr nullable(typeName, className, requiredProperties, propertyKey, prop); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + typeName = typeName.makeNullable(); + } + final propertySchema = allClasses[prop.ref.getUnformattedRef()]; if (propertySchema?.isNullable == true || isPropertyNullable) { @@ -812,6 +833,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr enumPropertyName, className, requiredProperties, propertyKey, prop); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + enumPropertyName = enumPropertyName.makeNullable(); + } + return ''' @JsonKey(${unknownEnumValue.jsonKey.substring(2)}$includeIfNullString) final $enumPropertyName ${generateFieldName(key)}; @@ -913,7 +939,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr List allEnumNames, List allEnumListNames, Map basicTypesMap, - List requiredParameters, + List requiredProperties, Map allClasses, ) { final typeName = _generateListPropertyTypeName( @@ -959,7 +985,12 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr if (prop.isNullable || options.nullableFields) { listPropertyName = nullable( - listPropertyName, className, requiredParameters, propertyKey, prop); + listPropertyName, className, requiredProperties, propertyKey, prop); + } + + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + listPropertyName = listPropertyName.makeNullable(); } return '$jsonKeyContent final $listPropertyName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; @@ -1033,6 +1064,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr nullable(typeName, className, requiredProperties, propertyKey, prop); } + if (requiredProperties.isNotEmpty && + !requiredProperties.contains(propertyKey)) { + typeName = typeName.makeNullable(); + } + return '\t$jsonKeyContent final $typeName $propertyName;${unknownEnumValue.fromJson}'; } @@ -1189,6 +1225,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyName, allEnumNames, allEnumListNames, + requiredProperties, )); } } @@ -1291,10 +1328,12 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr options.nullableFields || value.isNullable; - if (isNullableProperty) { - results += '\t\tthis.$fieldName,\n'; - } else { + final isRequiredProperty = requiredProperties.contains(key); + + if(isRequiredProperty || !isNullableProperty) { results += '\t\t$kRequired this.$fieldName,\n'; + }else{ + results += '\t\tthis.$fieldName,\n'; } }); From 6c2f1a7f21e131d664b0623980d1179c6c5bd7e5 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 12:33:52 +0300 Subject: [PATCH 29/67] Added check for object ref in body --- lib/src/code_generators/swagger_requests_generator.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 3aed2d1f..5a4cc87f 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -639,7 +639,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (ref != null) { final neededSchema = root.allSchemas[ref.getUnformattedRef()]; - if (kBasicTypesMap.containsKey(neededSchema?.type)) { + if (neededSchema?.type != 'object' && kBasicTypesMap.containsKey(neededSchema?.type)) { return kBasicTypesMap[neededSchema?.type]!; } } From e97337014ab465835529dbbc0afda7e88ff3affa Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 13:01:57 +0300 Subject: [PATCH 30/67] Fixed some things --- .../swagger_models_generator.dart | 33 ++++++++++--------- lib/src/models/generator_options.dart | 4 +-- lib/src/models/generator_options.g2.dart | 2 +- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index ec8a8e44..431bdcac 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -564,8 +564,15 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { - return options.nullableModels.contains(className) || - prop.isNullable == true; + if (options.nullableModels.contains(className) || prop.isNullable == true) { + return true; + } + + if (requiredProperties.contains(propertyKey)) { + return false; + } + + return options.nullableFields; } String nullable( @@ -633,8 +640,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; if (prop.isNullable || options.nullableFields) { - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + typeName = typeName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -703,8 +709,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; if (prop.isNullable || options.nullableFields) { - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + typeName = typeName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -777,8 +782,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; if (prop.isNullable || options.nullableFields) { - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + typeName = typeName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -829,8 +833,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var enumPropertyName = className.capitalize + key.capitalize; if (prop.isNullable || options.nullableFields) { - enumPropertyName = nullable( - enumPropertyName, className, requiredProperties, propertyKey, prop); + enumPropertyName = enumPropertyName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -984,8 +987,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; if (prop.isNullable || options.nullableFields) { - listPropertyName = nullable( - listPropertyName, className, requiredProperties, propertyKey, prop); + listPropertyName = listPropertyName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -1060,8 +1062,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr } if (prop.isNullable || options.nullableFields) { - typeName = - nullable(typeName, className, requiredProperties, propertyKey, prop); + typeName = typeName.makeNullable(); } if (requiredProperties.isNotEmpty && @@ -1330,9 +1331,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final isRequiredProperty = requiredProperties.contains(key); - if(isRequiredProperty || !isNullableProperty) { + if (isRequiredProperty || !isNullableProperty) { results += '\t\t$kRequired this.$fieldName,\n'; - }else{ + } else { results += '\t\tthis.$fieldName,\n'; } }); diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 1487ffee..f4c3ca24 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -37,7 +37,7 @@ class GeneratorOptions { this.overridenModels = const [], this.generateToJsonFor = const [], this.multipartFileType = 'List', - this.nullableFields = false, + this.nullableFields = true, }); /// Build options from a JSON map. @@ -50,7 +50,7 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool withBaseUrl; - @JsonKey(defaultValue: false) + @JsonKey(defaultValue: true) final bool nullableFields; @JsonKey(defaultValue: false) diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 60843370..97a95dca 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -84,7 +84,7 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( .toList() ?? [], multipartFileType: json['multipart_file_type'] as String? ?? 'List', - nullableFields: json['nullable_fields'] as bool? ?? false, + nullableFields: json['nullable_fields'] as bool? ?? true, ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => From 4fa3a11b61f75f0f06b994879aae2f1f5e1082b0 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 13:03:10 +0300 Subject: [PATCH 31/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index f105c09b..aea3a2a3 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -165,6 +165,7 @@ void main() { propertyName, [], [], + [], ); expect(result, contains(jsonKeyExpendedResult)); @@ -182,6 +183,7 @@ void main() { propertyName, [], [], + [], ); expect(result, contains(', includeIfNull: false')); @@ -195,6 +197,7 @@ void main() { propertyName, [], [], + [], ); expect(result.contains(', includeIfNull: false'), equals(false)); From 78966172dedcc88c6416a450748fa0ef96a8815e Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 13:04:58 +0300 Subject: [PATCH 32/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index aea3a2a3..496c7457 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -12,12 +12,14 @@ void main() { GeneratorOptions( inputFolder: '', outputFolder: '', + nullableFields: false, ), ); final generator2 = SwaggerModelsGeneratorV2( GeneratorOptions( inputFolder: '', outputFolder: '', + nullableFields: false, ), ); From 22af9f07087d0275577552d7d94595eadf9128e7 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 15:11:33 +0300 Subject: [PATCH 33/67] Fixed some things --- .../swagger_models_generator.dart | 55 ++++--------------- .../swagger_requests_generator.dart | 3 +- lib/src/models/generator_options.dart | 4 -- lib/src/models/generator_options.g2.dart | 2 - .../responses/swagger_schema.dart | 6 +- .../responses/swagger_schema.g2.dart | 2 +- 6 files changed, 16 insertions(+), 56 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 431bdcac..f9b21845 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -443,7 +443,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final includeIfNullString = generateIncludeIfNullString(); - if (typeName != kDynamic && (prop.isNullable || options.nullableFields)) { + if (typeName != kDynamic && prop.isNullable) { typeName = typeName.makeNullable(); } @@ -564,15 +564,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { - if (options.nullableModels.contains(className) || prop.isNullable == true) { - return true; - } - if (requiredProperties.contains(propertyKey)) { return false; } - return options.nullableFields; + return options.nullableModels.contains(className) || prop.isNullable; } String nullable( @@ -639,12 +635,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - if (prop.isNullable || options.nullableFields) { - typeName = typeName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -708,12 +699,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if (prop.isNullable || options.nullableFields) { - typeName = typeName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -781,12 +767,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if (prop.isNullable || options.nullableFields) { - typeName = typeName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -832,12 +813,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var enumPropertyName = className.capitalize + key.capitalize; - if (prop.isNullable || options.nullableFields) { - enumPropertyName = enumPropertyName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { enumPropertyName = enumPropertyName.makeNullable(); } @@ -986,12 +962,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - if (prop.isNullable || options.nullableFields) { - listPropertyName = listPropertyName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { listPropertyName = listPropertyName.makeNullable(); } @@ -1061,12 +1032,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += ')\n'; } - if (prop.isNullable || options.nullableFields) { - typeName = typeName.makeNullable(); - } - - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (prop.isNullable && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -1325,9 +1291,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyNames.add(fieldName); - final isNullableProperty = options.nullableModels.contains(className) || - options.nullableFields || - value.isNullable; + final isNullableProperty = + options.nullableModels.contains(className) || value.isNullable; final isRequiredProperty = requiredProperties.contains(key); diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 5a4cc87f..2abab3eb 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -448,8 +448,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { var allModelsString = ''; allModels.toSet().forEach((model) { + final validatedName = getValidatedClassName(model); allModelsString += - 'generatedMapping.putIfAbsent($model, () => $model.fromJsonFactory);\n'; + 'generatedMapping.putIfAbsent($validatedName, () => $validatedName.fromJsonFactory);\n'; }); return Code( diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index f4c3ca24..4be5e95f 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -37,7 +37,6 @@ class GeneratorOptions { this.overridenModels = const [], this.generateToJsonFor = const [], this.multipartFileType = 'List', - this.nullableFields = true, }); /// Build options from a JSON map. @@ -50,9 +49,6 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool withBaseUrl; - @JsonKey(defaultValue: true) - final bool nullableFields; - @JsonKey(defaultValue: false) final bool addBasePathToRequests; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 97a95dca..6050b4a8 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -84,14 +84,12 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( .toList() ?? [], multipartFileType: json['multipart_file_type'] as String? ?? 'List', - nullableFields: json['nullable_fields'] as bool? ?? true, ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => { 'use_path_for_request_names': instance.usePathForRequestNames, 'with_base_url': instance.withBaseUrl, - 'nullable_fields': instance.nullableFields, 'add_base_path_to_requests': instance.addBasePathToRequests, 'page_width': instance.pageWidth, 'override_to_string': instance.overrideToString, diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 579b8ad8..4ecf2459 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -21,7 +21,7 @@ class SwaggerSchema { this.required = const [], this.description = '', this.enumNames, - this.isNullable = false, + this.isNullable = true, this.hasAdditionalProperties = false, this.msEnum, }); @@ -76,7 +76,7 @@ class SwaggerSchema { @JsonKey(name: 'properties', defaultValue: {}) Map properties; - @JsonKey(name: 'nullable', defaultValue: false) + @JsonKey(name: 'nullable', defaultValue: true) bool isNullable; @JsonKey(name: 'schema') @@ -106,7 +106,7 @@ class SwaggerSchema { .toList() ..isNullable = (json[kIsNullable] ?? json[kNullable] ?? - false) as bool; + true) as bool; Map toJson() => { ..._$SwaggerSchemaToJson(this), diff --git a/lib/src/swagger_models/responses/swagger_schema.g2.dart b/lib/src/swagger_models/responses/swagger_schema.g2.dart index 73e1998d..af44df10 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g2.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g2.dart @@ -44,7 +44,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => enumNames: (json['enumNames'] as List?) ?.map((e) => e as String) .toList(), - isNullable: json['nullable'] as bool? ?? false, + isNullable: json['nullable'] as bool? ?? true, hasAdditionalProperties: json['additionalProperties'] == null ? false : _additionalsFromJson(json['additionalProperties']), From ddf6b4cd3e9be0a2d92a33a5e146a2188f6f92a4 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 15:34:32 +0300 Subject: [PATCH 34/67] 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 3359467f..0d338b55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.11.13 + +* Fixed different issues + # 2.11.12 * Added generation of const constructors diff --git a/pubspec.yaml b/pubspec.yaml index a620aa67..e2d99af2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.12 +version: 2.11.13 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 66dba0412dc27060b9dcdd16f4da9307681c0eac Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 20 Oct 2023 15:36:49 +0300 Subject: [PATCH 35/67] Removed not needed lines in tests --- test/generator_tests/models_generator_test.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 496c7457..aea3a2a3 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -12,14 +12,12 @@ void main() { GeneratorOptions( inputFolder: '', outputFolder: '', - nullableFields: false, ), ); final generator2 = SwaggerModelsGeneratorV2( GeneratorOptions( inputFolder: '', outputFolder: '', - nullableFields: false, ), ); From 8fcfbb0532cb7c3cd6a7fc95259b3e14370c8e43 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 1 Nov 2023 15:56:35 +0300 Subject: [PATCH 36/67] Fixed generation of nullable responses --- .../swagger_models_generator.dart | 29 +++++++++++++------ .../responses/swagger_schema.dart | 2 +- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index f9b21845..dafdfd25 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -443,7 +443,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final includeIfNullString = generateIncludeIfNullString(); - if (typeName != kDynamic && prop.isNullable) { + if (typeName != kDynamic && + (prop.isNullable || options.nullableModels.contains(typeName))) { typeName = typeName.makeNullable(); } @@ -635,7 +636,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -699,7 +701,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -744,7 +747,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName += options.modelPostfix; } - final isPropertyNullable = refSchema?.isNullable == true || + final isPropertyNullable = options.nullableModels.contains(className) || + refSchema?.isNullable == true || isNullable(className, requiredProperties, propertyKey, prop); final unknownEnumValue = generateEnumValue( @@ -767,13 +771,16 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } final propertySchema = allClasses[prop.ref.getUnformattedRef()]; - if (propertySchema?.isNullable == true || isPropertyNullable) { + if (propertySchema?.isNullable == true || + isPropertyNullable || + options.nullableModels.contains(className)) { typeName = typeName.makeNullable(); } @@ -813,7 +820,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var enumPropertyName = className.capitalize + key.capitalize; - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { enumPropertyName = enumPropertyName.makeNullable(); } @@ -962,7 +970,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { listPropertyName = listPropertyName.makeNullable(); } @@ -1012,6 +1021,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr defaultValue: prop.defaultValue, isList: false, isNullable: isNullable(className, requiredProperties, propertyKey, prop), + className: className, ); final dateToJsonValue = generateToJsonForDate(prop); @@ -1032,7 +1042,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += ')\n'; } - if (prop.isNullable && !requiredProperties.contains(propertyKey)) { + if ((prop.isNullable || options.nullableModels.contains(className)) && + !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 4ecf2459..a33d1121 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -106,7 +106,7 @@ class SwaggerSchema { .toList() ..isNullable = (json[kIsNullable] ?? json[kNullable] ?? - true) as bool; + false) as bool; Map toJson() => { ..._$SwaggerSchemaToJson(this), From 7448d28f3b0f0e25ddd7623c5110c38377a10bc3 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 1 Nov 2023 16:24:13 +0300 Subject: [PATCH 37/67] Added generation of DateTime --- lib/src/code_generators/swagger_additions_generator.dart | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index a14e25da..6b3cab31 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -198,10 +198,16 @@ class \$JsonSerializableConverter extends chopper.JsonConverter { return chopper.Response(response.base, null, error: response.error); } - if(ResultType == String) { + if (ResultType == String) { return response.copyWith(); } + if (ResultType == DateTime) { + return response.copyWith( + body: DateTime.parse((response.body as String).replaceAll('"', '')) + as ResultType); + } + final jsonRes = await super.convertResponse(response); return jsonRes.copyWith( body: \$jsonDecoder.decode(jsonRes.body) as ResultType); From c8c3522926badec1d55c0fa18711bab1a8e2ce40 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 1 Nov 2023 16:25:18 +0300 Subject: [PATCH 38/67] Updated pubspec and changelog --- CHANGELOG.md | 5 +++++ pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d338b55..c956b98d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # 2.11.13 +* Fixed return type nullability ([#670](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/670)) +* Fixed generation of DateTime return types + +# 2.12.1 + * Fixed different issues # 2.11.12 diff --git a/pubspec.yaml b/pubspec.yaml index e2d99af2..ff33efd3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.11.13 +version: 2.12.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 4c7f4df511f065616db4c627bcbebc2afba63558 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 1 Nov 2023 16:38:51 +0300 Subject: [PATCH 39/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index aea3a2a3..ef53e563 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -290,7 +290,7 @@ void main() { const className = 'Animals'; const propertyKey = 'Dog'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Dog')\n"; - const fieldExpectedResult = '\tfinal Pet dog'; + const fieldExpectedResult = '\tfinal Pet? dog'; final result = generator.generatePropertyContentBySchema( map, propertyName, @@ -315,7 +315,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet animals'; + const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -342,7 +342,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet animals'; + const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -367,7 +367,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'animals')\n"; - const fieldExpectedResult = 'final Pet animals'; + const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -392,7 +392,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: '\\\$with')\n"; - const fieldExpectedResult = 'final Pet \$with'; + const fieldExpectedResult = 'final Pet? \$with'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -420,7 +420,7 @@ void main() { const jsonKeyExpectedResult = "@JsonKey(name: 'Dog', defaultValue: [])"; - const propertyExpectedResult = 'final List dog'; + const propertyExpectedResult = 'final List? dog'; final result = generator.generateListPropertyContent( propertyName, propertyKey, @@ -480,7 +480,7 @@ void main() { {}, ); - expect(result, contains('final List dog;')); + expect(result, contains('final List? dog;')); }); test('Should return List by ref', () { @@ -503,7 +503,7 @@ void main() { {}, ); - expect(result, contains('final List dog;')); + expect(result, contains('final List? dog;')); }); }); From 6b9e1042b728f0feaeee5b75eb7a68d134b704fa Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 14:34:22 +0300 Subject: [PATCH 40/67] Fixed #669 Generation models from content schema allof --- .../swagger_models_generator.dart | 28 ++++++++++++++----- .../swagger_requests_generator.dart | 11 +++++++- .../responses/swagger_schema.dart | 8 ++++-- .../responses/swagger_schema.g2.dart | 2 ++ 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 9fedf0b3..d47b2c7d 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -3,6 +3,7 @@ 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/enum_model.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_generator_base.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/swagger_requests_generator.dart'; import 'package:swagger_dart_code_generator/src/exception_words.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -226,16 +227,29 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final requestText = operation.pascalCase; results['$pathText$requestText\$Response'] = neededSchema; - } else { - if (neededSchema?.type == kArray) { - final itemsSchema = neededSchema?.items; + } else if (neededSchema != null && + neededSchema.title.isNotEmpty && + neededSchema.allOf.isNotEmpty) { + final properties = {}; + + for (final allOf in neededSchema.allOf) { + properties.addAll(allOf.properties); - if (itemsSchema?.properties.isNotEmpty == true) { - final pathText = key.split('/').map((e) => e.pascalCase).join(); - final requestText = operation.pascalCase; - results['$pathText$requestText\$Response'] = neededSchema!; + if (allOf.ref.isNotEmpty) { + final schema = root.allSchemas[allOf.ref.getUnformattedRef()]; + properties.addAll(schema?.properties ?? {}); } } + + results[neededSchema.title] = SwaggerSchema(properties: properties); + } else if (neededSchema?.type == kArray) { + final itemsSchema = neededSchema?.items; + + if (itemsSchema?.properties.isNotEmpty == true) { + final pathText = key.split('/').map((e) => e.pascalCase).join(); + final requestText = operation.pascalCase; + results['$pathText$requestText\$Response'] = neededSchema!; + } } }); }); diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 2abab3eb..217605ff 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -640,7 +640,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (ref != null) { final neededSchema = root.allSchemas[ref.getUnformattedRef()]; - if (neededSchema?.type != 'object' && kBasicTypesMap.containsKey(neededSchema?.type)) { + if (neededSchema?.type != 'object' && + kBasicTypesMap.containsKey(neededSchema?.type)) { return kBasicTypesMap[neededSchema?.type]!; } } @@ -1150,6 +1151,14 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return kBasicTypesMap[type] ?? type; } + final contentSchema = content.schema; + + if (contentSchema != null && + contentSchema.allOf.isNotEmpty == true && + contentSchema.title.isNotEmpty) { + return contentSchema.title; + } + final schemaRef = content.schema?.ref ?? ''; if (schemaRef.isNotEmpty) { final allRefs = _getAllReusableObjects(swaggerRoot); diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index a33d1121..7025a06f 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -24,11 +24,15 @@ class SwaggerSchema { this.isNullable = true, this.hasAdditionalProperties = false, this.msEnum, + this.title = '', }); @JsonKey(name: 'type', defaultValue: '') String type; + @JsonKey(name: 'title', defaultValue: '') + String title; + @JsonKey(name: 'format', defaultValue: '') String format; @@ -104,9 +108,7 @@ class SwaggerSchema { ..enumNames = ((json[kEnumNames] ?? json[kEnumVarnames]) as List?) ?.map((e) => e as String) .toList() - ..isNullable = (json[kIsNullable] ?? - json[kNullable] ?? - false) as bool; + ..isNullable = (json[kIsNullable] ?? json[kNullable] ?? false) as bool; Map toJson() => { ..._$SwaggerSchemaToJson(this), diff --git a/lib/src/swagger_models/responses/swagger_schema.g2.dart b/lib/src/swagger_models/responses/swagger_schema.g2.dart index af44df10..38a705bc 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g2.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g2.dart @@ -41,6 +41,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => ? const [] : _requiredFromJson(json['required']), description: json['description'] as String? ?? '', + title: json['title'] as String? ?? '', enumNames: (json['enumNames'] as List?) ?.map((e) => e as String) .toList(), @@ -71,6 +72,7 @@ Map _$SwaggerSchemaToJson(SwaggerSchema instance) => 'oneOf': instance.oneOf, 'anyOf': instance.anyOf, 'allOf': instance.allOf, + 'title': instance.title, 'additionalProperties': instance.hasAdditionalProperties, 'enumNames': instance.enumNames, }; From c191faf30158172f37694c5efb363dde40591460 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 15:16:29 +0300 Subject: [PATCH 41/67] Fixed #665 generation putIfAbsent for response from content schema --- lib/src/code_generators/swagger_requests_generator.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 217605ff..f462868a 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -340,6 +340,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } } else if (successResponse?.schema?.properties.isNotEmpty == true) { results.add(response); + } else if (successResponse?.content?.schema?.properties.isNotEmpty == + true) { + results.add(response); } return results.where((element) => _isValidModelName(element)).toList(); From 313cea904450f4e986b310ce347281d25687ac89 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 15:54:55 +0300 Subject: [PATCH 42/67] Fixed generation of nullable and required properties --- .../swagger_models_generator.dart | 28 ++++++++++++------- .../swagger_requests_generator.dart | 2 +- .../responses/swagger_schema.dart | 6 ++-- .../responses/swagger_schema.g2.dart | 2 +- 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index d47b2c7d..3124edaa 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -458,7 +458,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final includeIfNullString = generateIncludeIfNullString(); if (typeName != kDynamic && - (prop.isNullable || options.nullableModels.contains(typeName))) { + (prop.isNullable == true || + options.nullableModels.contains(typeName))) { typeName = typeName.makeNullable(); } @@ -588,7 +589,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr return false; } - return options.nullableModels.contains(className) || prop.isNullable; + return options.nullableModels.contains(className) || + prop.isNullable == true; } String nullable( @@ -655,7 +657,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - if ((prop.isNullable || options.nullableModels.contains(className)) && + if ((prop.isNullable == true || + options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -720,7 +723,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if ((prop.isNullable || options.nullableModels.contains(className)) && + if ((prop.isNullable == true || + options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -790,7 +794,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if ((prop.isNullable || options.nullableModels.contains(className)) && + if ((prop.isNullable == true || + options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -839,7 +844,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var enumPropertyName = className.capitalize + key.capitalize; - if ((prop.isNullable || options.nullableModels.contains(className)) && + if ((prop.isNullable == true || + options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { enumPropertyName = enumPropertyName.makeNullable(); } @@ -989,7 +995,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - if ((prop.isNullable || options.nullableModels.contains(className)) && + if ((prop.isNullable == true || + options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { listPropertyName = listPropertyName.makeNullable(); } @@ -1061,7 +1068,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += ')\n'; } - if ((prop.isNullable || options.nullableModels.contains(className)) && + if (prop.isNullable == true || + options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -1321,8 +1329,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyNames.add(fieldName); - final isNullableProperty = - options.nullableModels.contains(className) || value.isNullable; + final isNullableProperty = options.nullableModels.contains(className) || + value.isNullable == true || !requiredProperties.contains(key); final isRequiredProperty = requiredProperties.contains(key); diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index f462868a..1c309acc 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -1178,7 +1178,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { var typeName = getValidatedClassName(schemaRef.getRef()).withPostfix(modelPostfix); - if (neededSchema.isNullable) { + if (neededSchema.isNullable == true) { typeName = typeName.makeNullable(); } diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 7025a06f..d086bbc0 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -21,7 +21,7 @@ class SwaggerSchema { this.required = const [], this.description = '', this.enumNames, - this.isNullable = true, + this.isNullable, this.hasAdditionalProperties = false, this.msEnum, this.title = '', @@ -80,8 +80,8 @@ class SwaggerSchema { @JsonKey(name: 'properties', defaultValue: {}) Map properties; - @JsonKey(name: 'nullable', defaultValue: true) - bool isNullable; + @JsonKey(name: 'nullable', defaultValue: null) + bool? isNullable; @JsonKey(name: 'schema') SwaggerSchema? schema; diff --git a/lib/src/swagger_models/responses/swagger_schema.g2.dart b/lib/src/swagger_models/responses/swagger_schema.g2.dart index 38a705bc..aa58c84e 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g2.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g2.dart @@ -45,7 +45,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => enumNames: (json['enumNames'] as List?) ?.map((e) => e as String) .toList(), - isNullable: json['nullable'] as bool? ?? true, + isNullable: json['nullable'] as bool? ?? null, hasAdditionalProperties: json['additionalProperties'] == null ? false : _additionalsFromJson(json['additionalProperties']), From 74bd5412120f68f09cf5dcb4d0d7e1b7d2b1c8ed Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 16:10:42 +0300 Subject: [PATCH 43/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index ef53e563..aea3a2a3 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -290,7 +290,7 @@ void main() { const className = 'Animals'; const propertyKey = 'Dog'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Dog')\n"; - const fieldExpectedResult = '\tfinal Pet? dog'; + const fieldExpectedResult = '\tfinal Pet dog'; final result = generator.generatePropertyContentBySchema( map, propertyName, @@ -315,7 +315,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -342,7 +342,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -367,7 +367,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'animals')\n"; - const fieldExpectedResult = 'final Pet? animals'; + const fieldExpectedResult = 'final Pet animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -392,7 +392,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: '\\\$with')\n"; - const fieldExpectedResult = 'final Pet? \$with'; + const fieldExpectedResult = 'final Pet \$with'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -420,7 +420,7 @@ void main() { const jsonKeyExpectedResult = "@JsonKey(name: 'Dog', defaultValue: [])"; - const propertyExpectedResult = 'final List? dog'; + const propertyExpectedResult = 'final List dog'; final result = generator.generateListPropertyContent( propertyName, propertyKey, @@ -480,7 +480,7 @@ void main() { {}, ); - expect(result, contains('final List? dog;')); + expect(result, contains('final List dog;')); }); test('Should return List by ref', () { @@ -503,7 +503,7 @@ void main() { {}, ); - expect(result, contains('final List? dog;')); + expect(result, contains('final List dog;')); }); }); From 07421cad44908379bb8a50f511b0e1f63ede65dd Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 17:11:03 +0300 Subject: [PATCH 44/67] Fixed some stuff related to nullable properties --- .../swagger_models_generator.dart | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 3124edaa..6c30a9c8 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -585,12 +585,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { - if (requiredProperties.contains(propertyKey)) { - return false; - } - - return options.nullableModels.contains(className) || - prop.isNullable == true; + return prop.isNullable == true || + options.nullableModels.contains(className) || + !requiredProperties.contains(propertyKey); } String nullable( @@ -717,14 +714,15 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName: typeName, defaultValue: prop.defaultValue, isList: false, + className: className, isNullable: isNullable(className, requiredProperties, propertyKey, prop), ); final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if ((prop.isNullable == true || - options.nullableModels.contains(className)) && + if (prop.isNullable == true || + options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -772,7 +770,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final isPropertyNullable = options.nullableModels.contains(className) || refSchema?.isNullable == true || - isNullable(className, requiredProperties, propertyKey, prop); + !requiredProperties.contains(propertyName); final unknownEnumValue = generateEnumValue( allEnumNames: allEnumNames, @@ -995,8 +993,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - if ((prop.isNullable == true || - options.nullableModels.contains(className)) && + if (prop.isNullable == true || + options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { listPropertyName = listPropertyName.makeNullable(); } @@ -1330,7 +1328,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyNames.add(fieldName); final isNullableProperty = options.nullableModels.contains(className) || - value.isNullable == true || !requiredProperties.contains(key); + value.isNullable == true || + !requiredProperties.contains(key); final isRequiredProperty = requiredProperties.contains(key); From d19f042f9419dcea8d4dc7c73d073068b7df5053 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 17:13:21 +0300 Subject: [PATCH 45/67] 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 4617c87e..fc9e7690 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 2.12.2 + +* Fixed generation of `nullable` and `required` fields ([#650](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/650)) +* Fixed generation of `putIfAbsent` for some models ([#665](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/665)) +* Fixed generation of some border-cased models ([#669](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/669)) + # 2.12.1 * Fixed return type nullability ([#670](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/670)) * Fixed generation of DateTime return types diff --git a/pubspec.yaml b/pubspec.yaml index ff33efd3..44a11b7e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.12.1 +version: 2.12.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 82db0ebcd2a1934b1cd6832f9af72aa79d32826e Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 17:14:03 +0300 Subject: [PATCH 46/67] Formatted code --- lib/swagger_dart_code_generator.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 32c0d9fa..ebd6cd1e 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -223,7 +223,7 @@ class SwaggerDartCodeGenerator implements Builder { allEnums, options, ); - + final imports = codeGenerator.generateImportsContent( fileNameWithoutExtension, models.contains('@JsonSerializable'), From 771958968afb0dd1bdd8195057e7857c9de16dbb Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 17:15:42 +0300 Subject: [PATCH 47/67] Formatted code --- test/generator_tests/enums_generator_test.dart | 1 - test/generator_tests/models_generator_test.dart | 4 +--- test/generator_tests/test_data.dart | 2 +- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/test/generator_tests/enums_generator_test.dart b/test/generator_tests/enums_generator_test.dart index cba6117b..071be261 100644 --- a/test/generator_tests/enums_generator_test.dart +++ b/test/generator_tests/enums_generator_test.dart @@ -4,7 +4,6 @@ import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; import 'package:swagger_dart_code_generator/src/swagger_models/requests/swagger_request_parameter.dart'; import 'package:test/test.dart'; - void main() { final generator = SwaggerEnumsGeneratorV3( GeneratorOptions( diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index aea3a2a3..84bd4c3a 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -266,9 +266,7 @@ void main() { }); test('Should return validate constructor property', () { - final map = { - 'Animal': SwaggerSchema() - }; + final map = {'Animal': SwaggerSchema()}; const expectedResult = 'this.animal'; final result = generator.generateConstructorPropertiesContent( className: '', diff --git a/test/generator_tests/test_data.dart b/test/generator_tests/test_data.dart index 35453068..a78a325e 100644 --- a/test/generator_tests/test_data.dart +++ b/test/generator_tests/test_data.dart @@ -831,4 +831,4 @@ const carsService = ''' } } } -'''; \ No newline at end of file +'''; From d277030128d1773a9ee6124d4b8a7429041c75c7 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 10 Nov 2023 17:19:17 +0300 Subject: [PATCH 48/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 84bd4c3a..852c6d5e 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -313,7 +313,7 @@ void main() { const className = 'Animals'; const jsonKeyExpectedResult = "\t@JsonKey(name: 'Animals')\n"; - const fieldExpectedResult = 'final Pet animals'; + const fieldExpectedResult = 'final Pet? animals'; final result = generator.generatePropertiesContent( SwaggerRoot.empty, map, @@ -418,7 +418,7 @@ void main() { const jsonKeyExpectedResult = "@JsonKey(name: 'Dog', defaultValue: [])"; - const propertyExpectedResult = 'final List dog'; + const propertyExpectedResult = 'final List? dog'; final result = generator.generateListPropertyContent( propertyName, propertyKey, @@ -478,7 +478,7 @@ void main() { {}, ); - expect(result, contains('final List dog;')); + expect(result, contains('final List? dog;')); }); test('Should return List by ref', () { @@ -501,7 +501,7 @@ void main() { {}, ); - expect(result, contains('final List dog;')); + expect(result, contains('final List? dog;')); }); }); From 73db345c07ea474e4f6b65f37a87f3f8754eb7f9 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 17 Nov 2023 11:43:54 +0300 Subject: [PATCH 49/67] Fixed generation of some enums inside classes --- lib/src/code_generators/swagger_generator_base.dart | 4 +++- lib/src/code_generators/swagger_models_generator.dart | 10 ++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/src/code_generators/swagger_generator_base.dart b/lib/src/code_generators/swagger_generator_base.dart index 60b939a9..db820dce 100644 --- a/lib/src/code_generators/swagger_generator_base.dart +++ b/lib/src/code_generators/swagger_generator_base.dart @@ -55,7 +55,9 @@ abstract class SwaggerGeneratorBase { return '\$$result'; } - return result.replaceFirst(options.cutFromModelNames, ''); + return result + .replaceFirst(options.cutFromModelNames, '') + .replaceAll('\$\$', '\$'); } String generateEnumName(String className, String enumName) { diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 6c30a9c8..594327af 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -161,10 +161,10 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { schema.items?.properties.isNotEmpty == true; properties.forEach((propertyKey, propSchema) { - final itemPart = shouldUseItemsProperties ? '\$Item' : ''; + final itemPart = shouldUseItemsProperties ? '\$Item\$' : '\$'; - final innerClassName = - '${getValidatedClassName(classKey)}$itemPart\$${getValidatedClassName(propertyKey)}'; + final innerClassName = getValidatedClassName( + '${getValidatedClassName(classKey)}$itemPart${getValidatedClassName(propertyKey)}'); if (propSchema.properties.isNotEmpty) { result[innerClassName] = propSchema; @@ -174,6 +174,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (items != null && items.properties.isNotEmpty) { propSchema.type = 'object'; + result['$innerClassName\$Item'] = items; } }); @@ -363,7 +364,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (parameter == null) return 'Object'; if (parameter.properties.isNotEmpty) { - return '${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}$modelPostfix'; + return getValidatedClassName( + '${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}$modelPostfix'); } if (parameter.items?.properties.isNotEmpty == true) { From fb2242c7bb2afa7cda868d391eec639f996bbb3f Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 17 Nov 2023 15:05:20 +0300 Subject: [PATCH 50/67] Implemented support of exploded parameters --- lib/src/code_generators/enum_model.dart | 6 +++ .../swagger_requests_generator.dart | 47 +++++++++++++++---- .../requests/swagger_request_parameter.dart | 4 ++ .../swagger_request_parameter.g2.dart | 2 + 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/lib/src/code_generators/enum_model.dart b/lib/src/code_generators/enum_model.dart index 9107c8c6..4ff61b92 100644 --- a/lib/src/code_generators/enum_model.dart +++ b/lib/src/code_generators/enum_model.dart @@ -134,6 +134,12 @@ enums.$name? ${name.camelCase}NullableFromJson( return enums.$name.values.firstWhereOrNull((e) => e.value == ${name.camelCase}) ?? defaultValue; } +String ${name.camelCase}ExplodedListToJson( + List? ${name.camelCase}) { + + return ${name.camelCase}?.map((e) => e.value!).join(',') ?? ''; +} + List<$type> ${name.camelCase}ListToJson( List? ${name.camelCase}) { diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 1c309acc..7c962d07 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -359,20 +359,22 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { Method _getPrivateMethod(Method method) { final parameters = method.optionalParameters.map((p) { + Parameter result = p; + if (p.type!.symbol!.startsWith('enums.')) { if (p.annotations .any((p0) => p0.code.toString().contains('symbol=Body'))) { - return p.copyWith(type: Reference('dynamic')); + result = result.copyWith(type: Reference('dynamic')); } else { - return p.copyWith(type: Reference('String?')); + result = result.copyWith(type: Reference('String?')); } } if (p.annotations.first.code.toString().contains('symbol=Header')) { if (p.type?.symbol?.startsWith('List<') == true) { - return p.copyWith(type: Reference('Iterable?')); + result = result.copyWith(type: Reference('Iterable?')); } - return p.copyWith(type: Reference('String?')); + result = result.copyWith(type: Reference('String?')); } if (p.type!.symbol!.startsWith('List')) { @@ -381,14 +383,21 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (listType.startsWith('enums.')) { if (p.annotations .any((p0) => p0.code.toString().contains('symbol=Body'))) { - return p.copyWith(type: Reference('dynamic')); + result = result.copyWith(type: Reference('dynamic')); } else { - return p.copyWith(type: Reference('List?')); + result = result.copyWith(type: Reference('List?')); } } } - return p; + if (p.annotations.first.code + .toString() + .contains('symbol=ExplodedQuery')) { + result = result.copyWith( + annotations: [refer('Query()')], type: Reference('String?')); + } + + return result; }); return Method( @@ -425,6 +434,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { List allModels, ) { final parametersListString = parameters.map((p) { + final isExposed = p.annotations.firstOrNull?.code + .toString() + .contains('symbol=ExplodedQuery') ?? + false; + if (p.type!.symbol!.startsWith('enums.')) { return '${p.name} : ${p.name}?.value?.toString()'; } @@ -442,7 +456,12 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { if (p.type!.symbol!.startsWith('List? ?? [], + explode: json['explode'] as bool? ?? false, ); Map _$SwaggerRequestParameterToJson( SwaggerRequestParameter instance) => { 'in': instance.inParameter, + 'explode': instance.explode, 'name': instance.name, 'description': instance.description, 'required': instance.isRequired, From 8c1fe97063b86bd516cece32b1459c3beb3ff241 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 17 Nov 2023 15:08:26 +0300 Subject: [PATCH 51/67] Pushed constants file --- lib/src/code_generators/constants.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 3b76d788..8b0a672b 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -88,6 +88,8 @@ const kCookie = 'cookie'; const kArray = 'array'; const kEnum = 'enum'; const kBody = 'body'; +const kQuery = 'query'; +const kExplodedQuery ='ExplodedQuery'; const kPartFile = 'partFile'; const kPart = 'part'; From 48dfe4a0761131d7c25e796a356aba1e85700116 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 15:14:25 +0300 Subject: [PATCH 52/67] Fixed generation of allOf for request bodies --- lib/src/code_generators/swagger_requests_generator.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 7c962d07..b1e5b81f 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -918,6 +918,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { typeName = _mapParameterName(schema.items!.type, schema.items!.format, options.modelPostfix) .asList(); + } else if (schema.allOf.length == 1 && + schema.allOf.first.ref.isNotEmpty) { + typeName = getValidatedClassName(schema.allOf.first.ref.getRef()); } else { typeName = _getRequestBodyTypeName( schema: schema, From 1158b4bf01a082eff28ef5b4fff2b5051b09a709 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 15:36:00 +0300 Subject: [PATCH 53/67] Implemented overriden_models functionality --- .../swagger_additions_generator.dart | 6 +++--- .../swagger_models_generator.dart | 13 +++++++++---- lib/src/models/generator_options.dart | 6 +++--- lib/src/models/generator_options.g2.dart | 9 +++++---- lib/swagger_dart_code_generator.dart | 18 ++++++++++-------- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index 6b3cab31..601a0c6d 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -49,9 +49,9 @@ class SwaggerAdditionsGenerator extends SwaggerGeneratorBase { final chopperPartImport = buildOnlyModels ? '' : "part '$swaggerFileName.swagger.chopper.dart';"; - final overridenModels = options.overridenModels.isEmpty - ? '' - : 'import \'overriden_models.dart\';'; + final overridenModels = options.overridenModels.containsKey(swaggerFileName) + ? 'import \'${swaggerFileName}_overriden.dart\';' + : ''; final chopperImports = buildOnlyModels ? '' diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 594327af..383e987e 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -38,8 +38,11 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { List allEnumNames, List allEnumListNames, Map allClasses, + String fileName, ) { - if (options.overridenModels.contains(getValidatedClassName(className))) { + if (options.overridenModels[fileName] + ?.contains(getValidatedClassName(className)) == + true) { return ''; } @@ -101,8 +104,9 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final itemClassName = '$className\$Item'; - if (options.overridenModels - .contains(getValidatedClassName(itemClassName))) { + if (options.overridenModels[fileName] + ?.contains(getValidatedClassName(itemClassName)) == + true) { return ''; } @@ -288,7 +292,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (classes['enum'] != null) { return ''; } - + final currentClass = classes[className]!; return generateModelClassContent( @@ -301,6 +305,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { allEnums.map((e) => e.name).toList(), allEnumListNames, classes, + fileName, ); }).join('\n'); diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 4be5e95f..394735d1 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -34,7 +34,7 @@ class GeneratorOptions { this.overrideEqualsAndHashcode = true, this.overrideToString = true, this.pageWidth, - this.overridenModels = const [], + this.overridenModels = const {}, this.generateToJsonFor = const [], this.multipartFileType = 'List', }); @@ -67,8 +67,8 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool withConverter; - @JsonKey(defaultValue: []) - final List overridenModels; + @JsonKey(defaultValue: {}) + final Map> overridenModels; @JsonKey(defaultValue: []) final List generateToJsonFor; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 6050b4a8..5ced0d8a 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -75,10 +75,11 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( json['override_equals_and_hashcode'] as bool? ?? true, overrideToString: json['override_to_string'] as bool? ?? true, pageWidth: json['page_width'] as int?, - overridenModels: (json['overriden_models'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], + overridenModels: (json['overriden_models'] as Map?)?.map( + (k, e) => MapEntry(k as String, + (e as List).map((e) => e as String).toList()), + ) ?? + {}, generateToJsonFor: (json['generate_to_json_for'] as List?) ?.map((e) => e as String) .toList() ?? diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index ebd6cd1e..76997f7d 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -64,16 +64,18 @@ Map> _generateExtensions(GeneratorOptions options) { _getAdditionalResultPath(options).replaceAll('\\', '/'); if (options.overridenModels.isNotEmpty) { - final path = normalize('${options.outputFolder}overriden_models.dart'); + for (final fileName in options.overridenModels.keys) { + final path = normalize('${options.outputFolder}${fileName}_overriden.dart'); - if (!Directory(options.outputFolder).existsSync()) { - Directory(options.outputFolder).createSync(); - } + if (!Directory(options.outputFolder).existsSync()) { + Directory(options.outputFolder).createSync(); + } - if (!File(path).existsSync()) { - File(path).createSync(); - File(path).writeAsString( - '//Put your overriden models here (${options.overridenModels.join(',')})'); + if (!File(path).existsSync()) { + File(path).createSync(); + File(path).writeAsString( + '//Put your overriden models here (${options.overridenModels[fileName]?.join(',')})'); + } } } From 0201193f3163cf153a13958323989c6f4f7aac63 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 15:53:44 +0300 Subject: [PATCH 54/67] Improved overriden models logic --- example/build.yaml | 6 +- example/lib/overriden_models.dart | 11 + .../swagger_generated_code/client_index.dart | 2 + .../overriden_models.dart | 9 - .../pet_service_json.enums.swagger.dart | 1 + .../pet_service_json.swagger.chopper.dart | 2 +- .../pet_service_json.swagger.dart | 359 ++++++++--------- .../pet_service_json.swagger.g.dart | 39 +- .../pet_service_swagger.enums.swagger.dart | 1 + .../pet_service_swagger.swagger.chopper.dart | 2 +- .../pet_service_swagger.swagger.dart | 381 ++++++++++++++---- .../pet_service_swagger.swagger.g.dart | 41 +- .../pet_service_yaml.enums.swagger.dart | 1 + .../pet_service_yaml.swagger.chopper.dart | 2 +- .../pet_service_yaml.swagger.dart | 381 ++++++++++++++---- .../pet_service_yaml.swagger.g.dart | 41 +- .../swagger_additions_generator.dart | 5 +- .../swagger_models_generator.dart | 14 +- lib/src/models/generator_options.dart | 27 +- lib/src/models/generator_options.g2.dart | 27 +- lib/swagger_dart_code_generator.dart | 16 - 21 files changed, 920 insertions(+), 448 deletions(-) create mode 100644 example/lib/overriden_models.dart delete mode 100644 example/lib/swagger_generated_code/overriden_models.dart diff --git a/example/build.yaml b/example/build.yaml index 3c3a5d82..416a295f 100644 --- a/example/build.yaml +++ b/example/build.yaml @@ -27,7 +27,11 @@ targets: additional_headers: - "Cache-Control" overriden_models: - - "Order" + - file_name: "pet_service_json" + import_url: "../overriden_models.dart" + overriden_models: + - "Pet" + - "Order" separate_models: false enums_case_sensitive: false cut_from_model_names: "ModelRenameV3" diff --git a/example/lib/overriden_models.dart b/example/lib/overriden_models.dart new file mode 100644 index 00000000..79c24edb --- /dev/null +++ b/example/lib/overriden_models.dart @@ -0,0 +1,11 @@ +class Pet { + static Pet fromJsonFactory(Map json) { + throw UnimplementedError(); + } +} + +class Order { + static Order fromJsonFactory(Map json) { + throw UnimplementedError(); + } +} diff --git a/example/lib/swagger_generated_code/client_index.dart b/example/lib/swagger_generated_code/client_index.dart index 8a987c96..00b3fd27 100644 --- a/example/lib/swagger_generated_code/client_index.dart +++ b/example/lib/swagger_generated_code/client_index.dart @@ -1,3 +1,5 @@ export 'pet_service_json.swagger.dart' show PetServiceJson; +export 'pet_service_json.swagger.dart' show PetServiceJson; export 'pet_service_swagger.swagger.dart' show PetServiceSwagger; export 'pet_service_yaml.swagger.dart' show PetServiceYaml; +export 'pet_service_yaml.swagger.dart' show PetServiceYaml; diff --git a/example/lib/swagger_generated_code/overriden_models.dart b/example/lib/swagger_generated_code/overriden_models.dart deleted file mode 100644 index 81736b3d..00000000 --- a/example/lib/swagger_generated_code/overriden_models.dart +++ /dev/null @@ -1,9 +0,0 @@ -class Order { - final String id; - - const Order(this.id); - - static const fromJsonFactory = _orderFromJson; - - static Order _orderFromJson(Map json) => Order(''); -} diff --git a/example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart b/example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart index 6cd0427b..1ea689ca 100644 --- a/example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart @@ -1,4 +1,5 @@ import 'package:json_annotation/json_annotation.dart'; +import 'package:collection/collection.dart'; enum OrderStatus { @JsonValue(null) diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart b/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart index 8a471d6b..04a3500d 100644 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart +++ b/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart @@ -58,7 +58,7 @@ class _$PetServiceJson extends PetServiceJson { @override Future>> _petFindByStatusGet({ - required String? status, + required List? status, String? cacheControl, }) { final Uri $url = Uri.parse('/pet/findByStatus'); diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.dart b/example/lib/swagger_generated_code/pet_service_json.swagger.dart index 8105d700..d48dd315 100644 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_json.swagger.dart @@ -4,11 +4,13 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'dart:convert'; -import 'overriden_models.dart'; +import '../overriden_models.dart'; import 'package:chopper/chopper.dart'; import 'client_mapping.dart'; import 'dart:async'; +import 'package:http/http.dart' as http; +import 'package:http/http.dart' show MultipartFile; import 'package:chopper/chopper.dart' as chopper; import 'pet_service_json.enums.swagger.dart' as enums; export 'pet_service_json.enums.swagger.dart'; @@ -24,7 +26,9 @@ part 'pet_service_json.swagger.g.dart'; abstract class PetServiceJson extends ChopperService { static PetServiceJson create({ ChopperClient? client, + http.Client? httpClient, Authenticator? authenticator, + Converter? converter, Uri? baseUrl, Iterable? interceptors, }) { @@ -34,8 +38,9 @@ abstract class PetServiceJson extends ChopperService { final newClient = ChopperClient( services: [_$PetServiceJson()], - converter: $JsonSerializableConverter(), + converter: converter ?? $JsonSerializableConverter(), interceptors: interceptors ?? [], + client: httpClient, authenticator: authenticator, baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); return _$PetServiceJson(newClient); @@ -45,11 +50,11 @@ abstract class PetServiceJson extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPost({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPost(body: body, cacheControl: cacheControl); + return _petPost(body: body, cacheControl: cacheControl?.toString()); } ///Add a new pet to the store @@ -64,11 +69,11 @@ abstract class PetServiceJson extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPut({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPut(body: body, cacheControl: cacheControl); + return _petPut(body: body, cacheControl: cacheControl?.toString()); } ///Update an existing pet @@ -82,20 +87,21 @@ abstract class PetServiceJson extends ChopperService { ///Finds Pets by status ///@param status Status values that need to be considered for filter Future>> petFindByStatusGet({ - required enums.PetFindByStatusGetStatus? status, - String? cacheControl, + required List? status, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petFindByStatusGet( - status: status?.value?.toString(), cacheControl: cacheControl); + status: petFindByStatusGetStatusListToJson(status), + cacheControl: cacheControl?.toString()); } ///Finds Pets by status ///@param status Status values that need to be considered for filter @Get(path: '/pet/findByStatus') Future>> _petFindByStatusGet({ - @Query('status') required String? status, + @Query() required List? status, @Header('Cache-Control') String? cacheControl, }); @@ -103,18 +109,19 @@ abstract class PetServiceJson extends ChopperService { ///@param tags Tags to filter by Future>> petFindByTagsGet({ required List? tags, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petFindByTagsGet(tags: tags, cacheControl: cacheControl); + return _petFindByTagsGet( + tags: tags, cacheControl: cacheControl?.toString()); } ///Finds Pets by tags ///@param tags Tags to filter by @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ - @Query('tags') required List? tags, + @Query() required List? tags, @Header('Cache-Control') String? cacheControl, }); @@ -122,13 +129,15 @@ abstract class PetServiceJson extends ChopperService { ///@param petId ID of pet to return Future> petPetIdGet({ required int? petId, - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petPetIdGet( - petId: petId, apiKey: apiKey, cacheControl: cacheControl); + petId: petId, + apiKey: apiKey?.toString(), + cacheControl: cacheControl?.toString()); } ///Find pet by ID @@ -148,10 +157,13 @@ abstract class PetServiceJson extends ChopperService { required int? petId, String? name, String? status, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdPost( - petId: petId, name: name, status: status, cacheControl: cacheControl); + petId: petId, + name: name, + status: status, + cacheControl: cacheControl?.toString()); } ///Updates a pet in the store with form data @@ -175,10 +187,12 @@ abstract class PetServiceJson extends ChopperService { Future petPetIdDelete({ String? apiKey, required int? petId, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdDelete( - apiKey: apiKey, petId: petId, cacheControl: cacheControl); + apiKey: apiKey?.toString(), + petId: petId, + cacheControl: cacheControl?.toString()); } ///Deletes a pet @@ -199,7 +213,7 @@ abstract class PetServiceJson extends ChopperService { required int? petId, String? additionalMetadata, List? file, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent( ApiResponse, () => ApiResponse.fromJsonFactory); @@ -208,7 +222,7 @@ abstract class PetServiceJson extends ChopperService { petId: petId, additionalMetadata: additionalMetadata, file: file, - cacheControl: cacheControl); + cacheControl: cacheControl?.toString()); } ///uploads an image @@ -228,10 +242,11 @@ abstract class PetServiceJson extends ChopperService { ///Returns pet inventories by status Future> storeInventoryGet({ - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { - return _storeInventoryGet(apiKey: apiKey, cacheControl: cacheControl); + return _storeInventoryGet( + apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); } ///Returns pet inventories by status @@ -245,11 +260,11 @@ abstract class PetServiceJson extends ChopperService { ///@param body order placed for purchasing the pet Future> storeOrderPost({ required Order? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderPost(body: body, cacheControl: cacheControl); + return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); } ///Place an order for a pet @@ -264,11 +279,12 @@ abstract class PetServiceJson extends ChopperService { ///@param orderId ID of pet that needs to be fetched Future> storeOrderOrderIdGet({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderOrderIdGet(orderId: orderId, cacheControl: cacheControl); + return _storeOrderOrderIdGet( + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Find purchase order by ID @@ -283,10 +299,10 @@ abstract class PetServiceJson extends ChopperService { ///@param orderId ID of the order that needs to be deleted Future storeOrderOrderIdDelete({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { return _storeOrderOrderIdDelete( - orderId: orderId, cacheControl: cacheControl); + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Delete purchase order by ID @@ -301,11 +317,11 @@ abstract class PetServiceJson extends ChopperService { ///@param body Created user object Future userPost({ required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userPost(body: body, cacheControl: cacheControl); + return _userPost(body: body, cacheControl: cacheControl?.toString()); } ///Create user @@ -320,9 +336,10 @@ abstract class PetServiceJson extends ChopperService { ///@param body List of user object Future userCreateWithArrayPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithArrayPost(body: body, cacheControl: cacheControl); + return _userCreateWithArrayPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -337,9 +354,10 @@ abstract class PetServiceJson extends ChopperService { ///@param body List of user object Future userCreateWithListPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithListPost(body: body, cacheControl: cacheControl); + return _userCreateWithListPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -356,10 +374,12 @@ abstract class PetServiceJson extends ChopperService { Future> userLoginGet({ required String? username, required String? password, - String? cacheControl, + dynamic cacheControl, }) { return _userLoginGet( - username: username, password: password, cacheControl: cacheControl); + username: username, + password: password, + cacheControl: cacheControl?.toString()); } ///Logs user into the system @@ -367,14 +387,14 @@ abstract class PetServiceJson extends ChopperService { ///@param password The password for login in clear text @Get(path: '/user/login') Future> _userLoginGet({ - @Query('username') required String? username, - @Query('password') required String? password, + @Query() required String? username, + @Query() required String? password, @Header('Cache-Control') String? cacheControl, }); ///Logs out current logged in user session - Future userLogoutGet({String? cacheControl}) { - return _userLogoutGet(cacheControl: cacheControl); + Future userLogoutGet({dynamic cacheControl}) { + return _userLogoutGet(cacheControl: cacheControl?.toString()); } ///Logs out current logged in user session @@ -386,11 +406,12 @@ abstract class PetServiceJson extends ChopperService { ///@param username The name that needs to be fetched. Use user1 for testing. Future> userUsernameGet({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userUsernameGet(username: username, cacheControl: cacheControl); + return _userUsernameGet( + username: username, cacheControl: cacheControl?.toString()); } ///Get user by user name @@ -407,12 +428,12 @@ abstract class PetServiceJson extends ChopperService { Future userUsernamePut({ required String? username, required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); return _userUsernamePut( - username: username, body: body, cacheControl: cacheControl); + username: username, body: body, cacheControl: cacheControl?.toString()); } ///Updated user @@ -429,9 +450,10 @@ abstract class PetServiceJson extends ChopperService { ///@param username The name that needs to be deleted Future userUsernameDelete({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { - return _userUsernameDelete(username: username, cacheControl: cacheControl); + return _userUsernameDelete( + username: username, cacheControl: cacheControl?.toString()); } ///Delete user @@ -445,7 +467,7 @@ abstract class PetServiceJson extends ChopperService { @JsonSerializable(explicitToJson: true) class Category { - Category({ + const Category({ this.id, this.name, }); @@ -453,13 +475,14 @@ class Category { factory Category.fromJson(Map json) => _$CategoryFromJson(json); + static const toJsonFactory = _$CategoryToJson; + Map toJson() => _$CategoryToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$CategoryFromJson; - static const toJsonFactory = _$CategoryToJson; - Map toJson() => _$CategoryToJson(this); @override bool operator ==(dynamic other) { @@ -482,11 +505,11 @@ class Category { } extension $CategoryExtension on Category { - Category copyWith({num? id, String? name}) { + Category copyWith({int? id, String? name}) { return Category(id: id ?? this.id, name: name ?? this.name); } - Category copyWithWrapped({Wrapped? id, Wrapped? name}) { + Category copyWithWrapped({Wrapped? id, Wrapped? name}) { return Category( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); @@ -495,7 +518,7 @@ extension $CategoryExtension on Category { @JsonSerializable(explicitToJson: true) class User { - User({ + const User({ this.id, this.username, this.firstName, @@ -508,8 +531,11 @@ class User { factory User.fromJson(Map json) => _$UserFromJson(json); + static const toJsonFactory = _$UserToJson; + Map toJson() => _$UserToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') final String? username; @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') @@ -525,8 +551,6 @@ class User { @JsonKey(name: 'userStatus', includeIfNull: false) final int? userStatus; static const fromJsonFactory = _$UserFromJson; - static const toJsonFactory = _$UserToJson; - Map toJson() => _$UserToJson(this); @override bool operator ==(dynamic other) { @@ -573,7 +597,7 @@ class User { extension $UserExtension on User { User copyWith( - {num? id, + {int? id, String? username, String? firstName, String? lastName, @@ -593,7 +617,7 @@ extension $UserExtension on User { } User copyWithWrapped( - {Wrapped? id, + {Wrapped? id, Wrapped? username, Wrapped? firstName, Wrapped? lastName, @@ -615,20 +639,21 @@ extension $UserExtension on User { @JsonSerializable(explicitToJson: true) class Tag { - Tag({ + const Tag({ this.id, this.name, }); factory Tag.fromJson(Map json) => _$TagFromJson(json); + static const toJsonFactory = _$TagToJson; + Map toJson() => _$TagToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$TagFromJson; - static const toJsonFactory = _$TagToJson; - Map toJson() => _$TagToJson(this); @override bool operator ==(dynamic other) { @@ -651,122 +676,20 @@ class Tag { } extension $TagExtension on Tag { - Tag copyWith({num? id, String? name}) { + Tag copyWith({int? id, String? name}) { return Tag(id: id ?? this.id, name: name ?? this.name); } - Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { + Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { return Tag( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); } } -@JsonSerializable(explicitToJson: true) -class Pet { - Pet({ - this.id, - this.category, - this.name, - this.photoUrls, - this.tags, - this.status, - }); - - factory Pet.fromJson(Map json) => _$PetFromJson(json); - - @JsonKey(name: 'id', includeIfNull: false) - final num? id; - @JsonKey(name: 'category', includeIfNull: false) - final Category? category; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - @JsonKey(name: 'photoUrls', includeIfNull: false) - final List? photoUrls; - @JsonKey(name: 'tags', includeIfNull: false) - final List? tags; - @JsonKey( - name: 'status', - includeIfNull: false, - toJson: petStatusToJson, - fromJson: petStatusFromJson, - ) - final enums.PetStatus? status; - static const fromJsonFactory = _$PetFromJson; - static const toJsonFactory = _$PetToJson; - Map toJson() => _$PetToJson(this); - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Pet && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.category, category) || - const DeepCollectionEquality() - .equals(other.category, category)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name)) && - (identical(other.photoUrls, photoUrls) || - const DeepCollectionEquality() - .equals(other.photoUrls, photoUrls)) && - (identical(other.tags, tags) || - const DeepCollectionEquality().equals(other.tags, tags)) && - (identical(other.status, status) || - const DeepCollectionEquality().equals(other.status, status))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(category) ^ - const DeepCollectionEquality().hash(name) ^ - const DeepCollectionEquality().hash(photoUrls) ^ - const DeepCollectionEquality().hash(tags) ^ - const DeepCollectionEquality().hash(status) ^ - runtimeType.hashCode; -} - -extension $PetExtension on Pet { - Pet copyWith( - {num? id, - Category? category, - String? name, - List? photoUrls, - List? tags, - enums.PetStatus? status}) { - return Pet( - id: id ?? this.id, - category: category ?? this.category, - name: name ?? this.name, - photoUrls: photoUrls ?? this.photoUrls, - tags: tags ?? this.tags, - status: status ?? this.status); - } - - Pet copyWithWrapped( - {Wrapped? id, - Wrapped? category, - Wrapped? name, - Wrapped?>? photoUrls, - Wrapped?>? tags, - Wrapped? status}) { - return Pet( - id: (id != null ? id.value : this.id), - category: (category != null ? category.value : this.category), - name: (name != null ? name.value : this.name), - photoUrls: (photoUrls != null ? photoUrls.value : this.photoUrls), - tags: (tags != null ? tags.value : this.tags), - status: (status != null ? status.value : this.status)); - } -} - @JsonSerializable(explicitToJson: true) class ApiResponse { - ApiResponse({ + const ApiResponse({ this.code, this.type, this.message, @@ -775,6 +698,9 @@ class ApiResponse { factory ApiResponse.fromJson(Map json) => _$ApiResponseFromJson(json); + static const toJsonFactory = _$ApiResponseToJson; + Map toJson() => _$ApiResponseToJson(this); + @JsonKey(name: 'code', includeIfNull: false) final int? code; @JsonKey(name: 'type', includeIfNull: false, defaultValue: '') @@ -782,8 +708,6 @@ class ApiResponse { @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') final String? message; static const fromJsonFactory = _$ApiResponseFromJson; - static const toJsonFactory = _$ApiResponseToJson; - Map toJson() => _$ApiResponseToJson(this); @override bool operator ==(dynamic other) { @@ -827,20 +751,41 @@ extension $ApiResponseExtension on ApiResponse { } } -String? orderStatusToJson(enums.OrderStatus? orderStatus) { +String? orderStatusNullableToJson(enums.OrderStatus? orderStatus) { return orderStatus?.value; } +String? orderStatusToJson(enums.OrderStatus orderStatus) { + return orderStatus.value; +} + enums.OrderStatus orderStatusFromJson( Object? orderStatus, [ enums.OrderStatus? defaultValue, ]) { - return enums.OrderStatus.values - .firstWhereOrNull((e) => e.value == orderStatus) ?? + return enums.OrderStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + orderStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.OrderStatus.swaggerGeneratedUnknown; } +enums.OrderStatus? orderStatusNullableFromJson( + Object? orderStatus, [ + enums.OrderStatus? defaultValue, +]) { + if (orderStatus == null) { + return null; + } + return enums.OrderStatus.values + .firstWhereOrNull((e) => e.value == orderStatus) ?? + defaultValue; +} + +String orderStatusExplodedListToJson(List? orderStatus) { + return orderStatus?.map((e) => e.value!).join(',') ?? ''; +} + List orderStatusListToJson(List? orderStatus) { if (orderStatus == null) { return []; @@ -871,19 +816,40 @@ List? orderStatusNullableListFromJson( return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); } -String? petStatusToJson(enums.PetStatus? petStatus) { +String? petStatusNullableToJson(enums.PetStatus? petStatus) { return petStatus?.value; } +String? petStatusToJson(enums.PetStatus petStatus) { + return petStatus.value; +} + enums.PetStatus petStatusFromJson( Object? petStatus, [ enums.PetStatus? defaultValue, ]) { - return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + return enums.PetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetStatus.swaggerGeneratedUnknown; } +enums.PetStatus? petStatusNullableFromJson( + Object? petStatus, [ + enums.PetStatus? defaultValue, +]) { + if (petStatus == null) { + return null; + } + return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + defaultValue; +} + +String petStatusExplodedListToJson(List? petStatus) { + return petStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petStatusListToJson(List? petStatus) { if (petStatus == null) { return []; @@ -914,21 +880,44 @@ List? petStatusNullableListFromJson( return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); } -String? petFindByStatusGetStatusToJson( +String? petFindByStatusGetStatusNullableToJson( enums.PetFindByStatusGetStatus? petFindByStatusGetStatus) { return petFindByStatusGetStatus?.value; } +String? petFindByStatusGetStatusToJson( + enums.PetFindByStatusGetStatus petFindByStatusGetStatus) { + return petFindByStatusGetStatus.value; +} + enums.PetFindByStatusGetStatus petFindByStatusGetStatusFromJson( Object? petFindByStatusGetStatus, [ enums.PetFindByStatusGetStatus? defaultValue, ]) { - return enums.PetFindByStatusGetStatus.values - .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + return enums.PetFindByStatusGetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petFindByStatusGetStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetFindByStatusGetStatus.swaggerGeneratedUnknown; } +enums.PetFindByStatusGetStatus? petFindByStatusGetStatusNullableFromJson( + Object? petFindByStatusGetStatus, [ + enums.PetFindByStatusGetStatus? defaultValue, +]) { + if (petFindByStatusGetStatus == null) { + return null; + } + return enums.PetFindByStatusGetStatus.values + .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + defaultValue; +} + +String petFindByStatusGetStatusExplodedListToJson( + List? petFindByStatusGetStatus) { + return petFindByStatusGetStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petFindByStatusGetStatusListToJson( List? petFindByStatusGetStatus) { if (petFindByStatusGetStatus == null) { @@ -1019,6 +1008,16 @@ class $JsonSerializableConverter extends chopper.JsonConverter { return chopper.Response(response.base, null, error: response.error); } + if (ResultType == String) { + return response.copyWith(); + } + + if (ResultType == DateTime) { + return response.copyWith( + body: DateTime.parse((response.body as String).replaceAll('"', '')) + as ResultType); + } + final jsonRes = await super.convertResponse(response); return jsonRes.copyWith( body: $jsonDecoder.decode(jsonRes.body) as ResultType); diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart b/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart index 63efd647..f1bb7df4 100644 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart +++ b/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart @@ -7,7 +7,7 @@ part of 'pet_service_json.swagger.dart'; // ************************************************************************** Category _$CategoryFromJson(Map json) => Category( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -26,7 +26,7 @@ Map _$CategoryToJson(Category instance) { } User _$UserFromJson(Map json) => User( - id: json['id'] as num?, + id: json['id'] as int?, username: json['username'] as String? ?? '', firstName: json['firstName'] as String? ?? '', lastName: json['lastName'] as String? ?? '', @@ -57,7 +57,7 @@ Map _$UserToJson(User instance) { } Tag _$TagFromJson(Map json) => Tag( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -75,39 +75,6 @@ Map _$TagToJson(Tag instance) { return val; } -Pet _$PetFromJson(Map json) => Pet( - id: json['id'] as num?, - category: json['category'] == null - ? null - : Category.fromJson(json['category'] as Map), - name: json['name'] as String? ?? '', - photoUrls: (json['photoUrls'] as List?) - ?.map((e) => e as String) - .toList(), - tags: (json['tags'] as List?) - ?.map((e) => Tag.fromJson(e as Map)) - .toList(), - status: petStatusFromJson(json['status']), - ); - -Map _$PetToJson(Pet instance) { - final val = {}; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('id', instance.id); - writeNotNull('category', instance.category?.toJson()); - writeNotNull('name', instance.name); - writeNotNull('photoUrls', instance.photoUrls); - writeNotNull('tags', instance.tags?.map((e) => e.toJson()).toList()); - writeNotNull('status', petStatusToJson(instance.status)); - return val; -} - ApiResponse _$ApiResponseFromJson(Map json) => ApiResponse( code: json['code'] as int?, type: json['type'] as String? ?? '', diff --git a/example/lib/swagger_generated_code/pet_service_swagger.enums.swagger.dart b/example/lib/swagger_generated_code/pet_service_swagger.enums.swagger.dart index 6cd0427b..1ea689ca 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.enums.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.enums.swagger.dart @@ -1,4 +1,5 @@ import 'package:json_annotation/json_annotation.dart'; +import 'package:collection/collection.dart'; enum OrderStatus { @JsonValue(null) diff --git a/example/lib/swagger_generated_code/pet_service_swagger.swagger.chopper.dart b/example/lib/swagger_generated_code/pet_service_swagger.swagger.chopper.dart index 15f92955..15ef88dc 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.swagger.chopper.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.swagger.chopper.dart @@ -58,7 +58,7 @@ class _$PetServiceSwagger extends PetServiceSwagger { @override Future>> _petFindByStatusGet({ - required String? status, + required List? status, String? cacheControl, }) { final Uri $url = Uri.parse('/pet/findByStatus'); diff --git a/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart b/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart index 25069bf0..de713a08 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart @@ -4,11 +4,12 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'dart:convert'; -import 'overriden_models.dart'; import 'package:chopper/chopper.dart'; import 'client_mapping.dart'; import 'dart:async'; +import 'package:http/http.dart' as http; +import 'package:http/http.dart' show MultipartFile; import 'package:chopper/chopper.dart' as chopper; import 'pet_service_swagger.enums.swagger.dart' as enums; export 'pet_service_swagger.enums.swagger.dart'; @@ -24,7 +25,9 @@ part 'pet_service_swagger.swagger.g.dart'; abstract class PetServiceSwagger extends ChopperService { static PetServiceSwagger create({ ChopperClient? client, + http.Client? httpClient, Authenticator? authenticator, + Converter? converter, Uri? baseUrl, Iterable? interceptors, }) { @@ -34,8 +37,9 @@ abstract class PetServiceSwagger extends ChopperService { final newClient = ChopperClient( services: [_$PetServiceSwagger()], - converter: $JsonSerializableConverter(), + converter: converter ?? $JsonSerializableConverter(), interceptors: interceptors ?? [], + client: httpClient, authenticator: authenticator, baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); return _$PetServiceSwagger(newClient); @@ -45,11 +49,11 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPost({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPost(body: body, cacheControl: cacheControl); + return _petPost(body: body, cacheControl: cacheControl?.toString()); } ///Add a new pet to the store @@ -64,11 +68,11 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPut({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPut(body: body, cacheControl: cacheControl); + return _petPut(body: body, cacheControl: cacheControl?.toString()); } ///Update an existing pet @@ -82,20 +86,21 @@ abstract class PetServiceSwagger extends ChopperService { ///Finds Pets by status ///@param status Status values that need to be considered for filter Future>> petFindByStatusGet({ - required enums.PetFindByStatusGetStatus? status, - String? cacheControl, + required List? status, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petFindByStatusGet( - status: status?.value?.toString(), cacheControl: cacheControl); + status: petFindByStatusGetStatusListToJson(status), + cacheControl: cacheControl?.toString()); } ///Finds Pets by status ///@param status Status values that need to be considered for filter @Get(path: '/pet/findByStatus') Future>> _petFindByStatusGet({ - @Query('status') required String? status, + @Query() required List? status, @Header('Cache-Control') String? cacheControl, }); @@ -103,18 +108,19 @@ abstract class PetServiceSwagger extends ChopperService { ///@param tags Tags to filter by Future>> petFindByTagsGet({ required List? tags, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petFindByTagsGet(tags: tags, cacheControl: cacheControl); + return _petFindByTagsGet( + tags: tags, cacheControl: cacheControl?.toString()); } ///Finds Pets by tags ///@param tags Tags to filter by @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ - @Query('tags') required List? tags, + @Query() required List? tags, @Header('Cache-Control') String? cacheControl, }); @@ -122,13 +128,15 @@ abstract class PetServiceSwagger extends ChopperService { ///@param petId ID of pet to return Future> petPetIdGet({ required int? petId, - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petPetIdGet( - petId: petId, apiKey: apiKey, cacheControl: cacheControl); + petId: petId, + apiKey: apiKey?.toString(), + cacheControl: cacheControl?.toString()); } ///Find pet by ID @@ -148,10 +156,13 @@ abstract class PetServiceSwagger extends ChopperService { required int? petId, String? name, String? status, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdPost( - petId: petId, name: name, status: status, cacheControl: cacheControl); + petId: petId, + name: name, + status: status, + cacheControl: cacheControl?.toString()); } ///Updates a pet in the store with form data @@ -175,10 +186,12 @@ abstract class PetServiceSwagger extends ChopperService { Future petPetIdDelete({ String? apiKey, required int? petId, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdDelete( - apiKey: apiKey, petId: petId, cacheControl: cacheControl); + apiKey: apiKey?.toString(), + petId: petId, + cacheControl: cacheControl?.toString()); } ///Deletes a pet @@ -199,7 +212,7 @@ abstract class PetServiceSwagger extends ChopperService { required int? petId, String? additionalMetadata, List? file, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent( ApiResponse, () => ApiResponse.fromJsonFactory); @@ -208,7 +221,7 @@ abstract class PetServiceSwagger extends ChopperService { petId: petId, additionalMetadata: additionalMetadata, file: file, - cacheControl: cacheControl); + cacheControl: cacheControl?.toString()); } ///uploads an image @@ -228,10 +241,11 @@ abstract class PetServiceSwagger extends ChopperService { ///Returns pet inventories by status Future> storeInventoryGet({ - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { - return _storeInventoryGet(apiKey: apiKey, cacheControl: cacheControl); + return _storeInventoryGet( + apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); } ///Returns pet inventories by status @@ -245,11 +259,11 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body order placed for purchasing the pet Future> storeOrderPost({ required Order? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderPost(body: body, cacheControl: cacheControl); + return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); } ///Place an order for a pet @@ -264,11 +278,12 @@ abstract class PetServiceSwagger extends ChopperService { ///@param orderId ID of pet that needs to be fetched Future> storeOrderOrderIdGet({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderOrderIdGet(orderId: orderId, cacheControl: cacheControl); + return _storeOrderOrderIdGet( + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Find purchase order by ID @@ -283,10 +298,10 @@ abstract class PetServiceSwagger extends ChopperService { ///@param orderId ID of the order that needs to be deleted Future storeOrderOrderIdDelete({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { return _storeOrderOrderIdDelete( - orderId: orderId, cacheControl: cacheControl); + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Delete purchase order by ID @@ -301,11 +316,11 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body Created user object Future userPost({ required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userPost(body: body, cacheControl: cacheControl); + return _userPost(body: body, cacheControl: cacheControl?.toString()); } ///Create user @@ -320,9 +335,10 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body List of user object Future userCreateWithArrayPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithArrayPost(body: body, cacheControl: cacheControl); + return _userCreateWithArrayPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -337,9 +353,10 @@ abstract class PetServiceSwagger extends ChopperService { ///@param body List of user object Future userCreateWithListPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithListPost(body: body, cacheControl: cacheControl); + return _userCreateWithListPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -356,10 +373,12 @@ abstract class PetServiceSwagger extends ChopperService { Future> userLoginGet({ required String? username, required String? password, - String? cacheControl, + dynamic cacheControl, }) { return _userLoginGet( - username: username, password: password, cacheControl: cacheControl); + username: username, + password: password, + cacheControl: cacheControl?.toString()); } ///Logs user into the system @@ -367,14 +386,14 @@ abstract class PetServiceSwagger extends ChopperService { ///@param password The password for login in clear text @Get(path: '/user/login') Future> _userLoginGet({ - @Query('username') required String? username, - @Query('password') required String? password, + @Query() required String? username, + @Query() required String? password, @Header('Cache-Control') String? cacheControl, }); ///Logs out current logged in user session - Future userLogoutGet({String? cacheControl}) { - return _userLogoutGet(cacheControl: cacheControl); + Future userLogoutGet({dynamic cacheControl}) { + return _userLogoutGet(cacheControl: cacheControl?.toString()); } ///Logs out current logged in user session @@ -386,11 +405,12 @@ abstract class PetServiceSwagger extends ChopperService { ///@param username The name that needs to be fetched. Use user1 for testing. Future> userUsernameGet({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userUsernameGet(username: username, cacheControl: cacheControl); + return _userUsernameGet( + username: username, cacheControl: cacheControl?.toString()); } ///Get user by user name @@ -407,12 +427,12 @@ abstract class PetServiceSwagger extends ChopperService { Future userUsernamePut({ required String? username, required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); return _userUsernamePut( - username: username, body: body, cacheControl: cacheControl); + username: username, body: body, cacheControl: cacheControl?.toString()); } ///Updated user @@ -429,9 +449,10 @@ abstract class PetServiceSwagger extends ChopperService { ///@param username The name that needs to be deleted Future userUsernameDelete({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { - return _userUsernameDelete(username: username, cacheControl: cacheControl); + return _userUsernameDelete( + username: username, cacheControl: cacheControl?.toString()); } ///Delete user @@ -443,9 +464,113 @@ abstract class PetServiceSwagger extends ChopperService { }); } +@JsonSerializable(explicitToJson: true) +class Order { + const Order({ + this.id, + this.petId, + this.quantity, + this.shipDate, + this.status, + this.complete, + }); + + factory Order.fromJson(Map json) => _$OrderFromJson(json); + + static const toJsonFactory = _$OrderToJson; + Map toJson() => _$OrderToJson(this); + + @JsonKey(name: 'id', includeIfNull: false) + final int? id; + @JsonKey(name: 'petId', includeIfNull: false) + final int? petId; + @JsonKey(name: 'quantity', includeIfNull: false) + final int? quantity; + @JsonKey(name: 'shipDate', includeIfNull: false) + final DateTime? shipDate; + @JsonKey( + name: 'status', + includeIfNull: false, + toJson: orderStatusNullableToJson, + fromJson: orderStatusNullableFromJson, + ) + final enums.OrderStatus? status; + @JsonKey(name: 'complete', includeIfNull: false, defaultValue: false) + final bool? complete; + static const fromJsonFactory = _$OrderFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is Order && + (identical(other.id, id) || + const DeepCollectionEquality().equals(other.id, id)) && + (identical(other.petId, petId) || + const DeepCollectionEquality().equals(other.petId, petId)) && + (identical(other.quantity, quantity) || + const DeepCollectionEquality() + .equals(other.quantity, quantity)) && + (identical(other.shipDate, shipDate) || + const DeepCollectionEquality() + .equals(other.shipDate, shipDate)) && + (identical(other.status, status) || + const DeepCollectionEquality().equals(other.status, status)) && + (identical(other.complete, complete) || + const DeepCollectionEquality() + .equals(other.complete, complete))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(id) ^ + const DeepCollectionEquality().hash(petId) ^ + const DeepCollectionEquality().hash(quantity) ^ + const DeepCollectionEquality().hash(shipDate) ^ + const DeepCollectionEquality().hash(status) ^ + const DeepCollectionEquality().hash(complete) ^ + runtimeType.hashCode; +} + +extension $OrderExtension on Order { + Order copyWith( + {int? id, + int? petId, + int? quantity, + DateTime? shipDate, + enums.OrderStatus? status, + bool? complete}) { + return Order( + id: id ?? this.id, + petId: petId ?? this.petId, + quantity: quantity ?? this.quantity, + shipDate: shipDate ?? this.shipDate, + status: status ?? this.status, + complete: complete ?? this.complete); + } + + Order copyWithWrapped( + {Wrapped? id, + Wrapped? petId, + Wrapped? quantity, + Wrapped? shipDate, + Wrapped? status, + Wrapped? complete}) { + return Order( + id: (id != null ? id.value : this.id), + petId: (petId != null ? petId.value : this.petId), + quantity: (quantity != null ? quantity.value : this.quantity), + shipDate: (shipDate != null ? shipDate.value : this.shipDate), + status: (status != null ? status.value : this.status), + complete: (complete != null ? complete.value : this.complete)); + } +} + @JsonSerializable(explicitToJson: true) class Category { - Category({ + const Category({ this.id, this.name, }); @@ -453,13 +578,14 @@ class Category { factory Category.fromJson(Map json) => _$CategoryFromJson(json); + static const toJsonFactory = _$CategoryToJson; + Map toJson() => _$CategoryToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$CategoryFromJson; - static const toJsonFactory = _$CategoryToJson; - Map toJson() => _$CategoryToJson(this); @override bool operator ==(dynamic other) { @@ -482,11 +608,11 @@ class Category { } extension $CategoryExtension on Category { - Category copyWith({num? id, String? name}) { + Category copyWith({int? id, String? name}) { return Category(id: id ?? this.id, name: name ?? this.name); } - Category copyWithWrapped({Wrapped? id, Wrapped? name}) { + Category copyWithWrapped({Wrapped? id, Wrapped? name}) { return Category( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); @@ -495,7 +621,7 @@ extension $CategoryExtension on Category { @JsonSerializable(explicitToJson: true) class User { - User({ + const User({ this.id, this.username, this.firstName, @@ -508,8 +634,11 @@ class User { factory User.fromJson(Map json) => _$UserFromJson(json); + static const toJsonFactory = _$UserToJson; + Map toJson() => _$UserToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') final String? username; @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') @@ -525,8 +654,6 @@ class User { @JsonKey(name: 'userStatus', includeIfNull: false) final int? userStatus; static const fromJsonFactory = _$UserFromJson; - static const toJsonFactory = _$UserToJson; - Map toJson() => _$UserToJson(this); @override bool operator ==(dynamic other) { @@ -573,7 +700,7 @@ class User { extension $UserExtension on User { User copyWith( - {num? id, + {int? id, String? username, String? firstName, String? lastName, @@ -593,7 +720,7 @@ extension $UserExtension on User { } User copyWithWrapped( - {Wrapped? id, + {Wrapped? id, Wrapped? username, Wrapped? firstName, Wrapped? lastName, @@ -615,20 +742,21 @@ extension $UserExtension on User { @JsonSerializable(explicitToJson: true) class Tag { - Tag({ + const Tag({ this.id, this.name, }); factory Tag.fromJson(Map json) => _$TagFromJson(json); + static const toJsonFactory = _$TagToJson; + Map toJson() => _$TagToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$TagFromJson; - static const toJsonFactory = _$TagToJson; - Map toJson() => _$TagToJson(this); @override bool operator ==(dynamic other) { @@ -651,11 +779,11 @@ class Tag { } extension $TagExtension on Tag { - Tag copyWith({num? id, String? name}) { + Tag copyWith({int? id, String? name}) { return Tag(id: id ?? this.id, name: name ?? this.name); } - Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { + Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { return Tag( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); @@ -664,19 +792,22 @@ extension $TagExtension on Tag { @JsonSerializable(explicitToJson: true) class Pet { - Pet({ + const Pet({ this.id, this.category, - this.name, - this.photoUrls, + required this.name, + required this.photoUrls, this.tags, this.status, }); factory Pet.fromJson(Map json) => _$PetFromJson(json); + static const toJsonFactory = _$PetToJson; + Map toJson() => _$PetToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'category', includeIfNull: false) final Category? category; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') @@ -688,13 +819,11 @@ class Pet { @JsonKey( name: 'status', includeIfNull: false, - toJson: petStatusToJson, - fromJson: petStatusFromJson, + toJson: petStatusNullableToJson, + fromJson: petStatusNullableFromJson, ) final enums.PetStatus? status; static const fromJsonFactory = _$PetFromJson; - static const toJsonFactory = _$PetToJson; - Map toJson() => _$PetToJson(this); @override bool operator ==(dynamic other) { @@ -732,7 +861,7 @@ class Pet { extension $PetExtension on Pet { Pet copyWith( - {num? id, + {int? id, Category? category, String? name, List? photoUrls, @@ -748,7 +877,7 @@ extension $PetExtension on Pet { } Pet copyWithWrapped( - {Wrapped? id, + {Wrapped? id, Wrapped? category, Wrapped? name, Wrapped?>? photoUrls, @@ -766,7 +895,7 @@ extension $PetExtension on Pet { @JsonSerializable(explicitToJson: true) class ApiResponse { - ApiResponse({ + const ApiResponse({ this.code, this.type, this.message, @@ -775,6 +904,9 @@ class ApiResponse { factory ApiResponse.fromJson(Map json) => _$ApiResponseFromJson(json); + static const toJsonFactory = _$ApiResponseToJson; + Map toJson() => _$ApiResponseToJson(this); + @JsonKey(name: 'code', includeIfNull: false) final int? code; @JsonKey(name: 'type', includeIfNull: false, defaultValue: '') @@ -782,8 +914,6 @@ class ApiResponse { @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') final String? message; static const fromJsonFactory = _$ApiResponseFromJson; - static const toJsonFactory = _$ApiResponseToJson; - Map toJson() => _$ApiResponseToJson(this); @override bool operator ==(dynamic other) { @@ -827,20 +957,41 @@ extension $ApiResponseExtension on ApiResponse { } } -String? orderStatusToJson(enums.OrderStatus? orderStatus) { +String? orderStatusNullableToJson(enums.OrderStatus? orderStatus) { return orderStatus?.value; } +String? orderStatusToJson(enums.OrderStatus orderStatus) { + return orderStatus.value; +} + enums.OrderStatus orderStatusFromJson( Object? orderStatus, [ enums.OrderStatus? defaultValue, ]) { - return enums.OrderStatus.values - .firstWhereOrNull((e) => e.value == orderStatus) ?? + return enums.OrderStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + orderStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.OrderStatus.swaggerGeneratedUnknown; } +enums.OrderStatus? orderStatusNullableFromJson( + Object? orderStatus, [ + enums.OrderStatus? defaultValue, +]) { + if (orderStatus == null) { + return null; + } + return enums.OrderStatus.values + .firstWhereOrNull((e) => e.value == orderStatus) ?? + defaultValue; +} + +String orderStatusExplodedListToJson(List? orderStatus) { + return orderStatus?.map((e) => e.value!).join(',') ?? ''; +} + List orderStatusListToJson(List? orderStatus) { if (orderStatus == null) { return []; @@ -871,19 +1022,40 @@ List? orderStatusNullableListFromJson( return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); } -String? petStatusToJson(enums.PetStatus? petStatus) { +String? petStatusNullableToJson(enums.PetStatus? petStatus) { return petStatus?.value; } +String? petStatusToJson(enums.PetStatus petStatus) { + return petStatus.value; +} + enums.PetStatus petStatusFromJson( Object? petStatus, [ enums.PetStatus? defaultValue, ]) { - return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + return enums.PetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetStatus.swaggerGeneratedUnknown; } +enums.PetStatus? petStatusNullableFromJson( + Object? petStatus, [ + enums.PetStatus? defaultValue, +]) { + if (petStatus == null) { + return null; + } + return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + defaultValue; +} + +String petStatusExplodedListToJson(List? petStatus) { + return petStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petStatusListToJson(List? petStatus) { if (petStatus == null) { return []; @@ -914,21 +1086,44 @@ List? petStatusNullableListFromJson( return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); } -String? petFindByStatusGetStatusToJson( +String? petFindByStatusGetStatusNullableToJson( enums.PetFindByStatusGetStatus? petFindByStatusGetStatus) { return petFindByStatusGetStatus?.value; } +String? petFindByStatusGetStatusToJson( + enums.PetFindByStatusGetStatus petFindByStatusGetStatus) { + return petFindByStatusGetStatus.value; +} + enums.PetFindByStatusGetStatus petFindByStatusGetStatusFromJson( Object? petFindByStatusGetStatus, [ enums.PetFindByStatusGetStatus? defaultValue, ]) { - return enums.PetFindByStatusGetStatus.values - .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + return enums.PetFindByStatusGetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petFindByStatusGetStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetFindByStatusGetStatus.swaggerGeneratedUnknown; } +enums.PetFindByStatusGetStatus? petFindByStatusGetStatusNullableFromJson( + Object? petFindByStatusGetStatus, [ + enums.PetFindByStatusGetStatus? defaultValue, +]) { + if (petFindByStatusGetStatus == null) { + return null; + } + return enums.PetFindByStatusGetStatus.values + .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + defaultValue; +} + +String petFindByStatusGetStatusExplodedListToJson( + List? petFindByStatusGetStatus) { + return petFindByStatusGetStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petFindByStatusGetStatusListToJson( List? petFindByStatusGetStatus) { if (petFindByStatusGetStatus == null) { @@ -1019,6 +1214,16 @@ class $JsonSerializableConverter extends chopper.JsonConverter { return chopper.Response(response.base, null, error: response.error); } + if (ResultType == String) { + return response.copyWith(); + } + + if (ResultType == DateTime) { + return response.copyWith( + body: DateTime.parse((response.body as String).replaceAll('"', '')) + as ResultType); + } + final jsonRes = await super.convertResponse(response); return jsonRes.copyWith( body: $jsonDecoder.decode(jsonRes.body) as ResultType); diff --git a/example/lib/swagger_generated_code/pet_service_swagger.swagger.g.dart b/example/lib/swagger_generated_code/pet_service_swagger.swagger.g.dart index c08df232..9a11db64 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.swagger.g.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.swagger.g.dart @@ -6,8 +6,37 @@ part of 'pet_service_swagger.swagger.dart'; // JsonSerializableGenerator // ************************************************************************** +Order _$OrderFromJson(Map json) => Order( + id: json['id'] as int?, + petId: json['petId'] as int?, + quantity: json['quantity'] as int?, + shipDate: json['shipDate'] == null + ? null + : DateTime.parse(json['shipDate'] as String), + status: orderStatusNullableFromJson(json['status']), + complete: json['complete'] as bool? ?? false, + ); + +Map _$OrderToJson(Order instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('id', instance.id); + writeNotNull('petId', instance.petId); + writeNotNull('quantity', instance.quantity); + writeNotNull('shipDate', instance.shipDate?.toIso8601String()); + writeNotNull('status', orderStatusNullableToJson(instance.status)); + writeNotNull('complete', instance.complete); + return val; +} + Category _$CategoryFromJson(Map json) => Category( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -26,7 +55,7 @@ Map _$CategoryToJson(Category instance) { } User _$UserFromJson(Map json) => User( - id: json['id'] as num?, + id: json['id'] as int?, username: json['username'] as String? ?? '', firstName: json['firstName'] as String? ?? '', lastName: json['lastName'] as String? ?? '', @@ -57,7 +86,7 @@ Map _$UserToJson(User instance) { } Tag _$TagFromJson(Map json) => Tag( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -76,7 +105,7 @@ Map _$TagToJson(Tag instance) { } Pet _$PetFromJson(Map json) => Pet( - id: json['id'] as num?, + id: json['id'] as int?, category: json['category'] == null ? null : Category.fromJson(json['category'] as Map), @@ -87,7 +116,7 @@ Pet _$PetFromJson(Map json) => Pet( tags: (json['tags'] as List?) ?.map((e) => Tag.fromJson(e as Map)) .toList(), - status: petStatusFromJson(json['status']), + status: petStatusNullableFromJson(json['status']), ); Map _$PetToJson(Pet instance) { @@ -104,7 +133,7 @@ Map _$PetToJson(Pet instance) { writeNotNull('name', instance.name); writeNotNull('photoUrls', instance.photoUrls); writeNotNull('tags', instance.tags?.map((e) => e.toJson()).toList()); - writeNotNull('status', petStatusToJson(instance.status)); + writeNotNull('status', petStatusNullableToJson(instance.status)); return val; } diff --git a/example/lib/swagger_generated_code/pet_service_yaml.enums.swagger.dart b/example/lib/swagger_generated_code/pet_service_yaml.enums.swagger.dart index 6cd0427b..1ea689ca 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.enums.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.enums.swagger.dart @@ -1,4 +1,5 @@ import 'package:json_annotation/json_annotation.dart'; +import 'package:collection/collection.dart'; enum OrderStatus { @JsonValue(null) diff --git a/example/lib/swagger_generated_code/pet_service_yaml.swagger.chopper.dart b/example/lib/swagger_generated_code/pet_service_yaml.swagger.chopper.dart index 08063eba..053fcca7 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.swagger.chopper.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.swagger.chopper.dart @@ -58,7 +58,7 @@ class _$PetServiceYaml extends PetServiceYaml { @override Future>> _petFindByStatusGet({ - required String? status, + required List? status, String? cacheControl, }) { final Uri $url = Uri.parse('/pet/findByStatus'); diff --git a/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart b/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart index 51291308..a1c5f657 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart @@ -4,11 +4,12 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'dart:convert'; -import 'overriden_models.dart'; import 'package:chopper/chopper.dart'; import 'client_mapping.dart'; import 'dart:async'; +import 'package:http/http.dart' as http; +import 'package:http/http.dart' show MultipartFile; import 'package:chopper/chopper.dart' as chopper; import 'pet_service_yaml.enums.swagger.dart' as enums; export 'pet_service_yaml.enums.swagger.dart'; @@ -24,7 +25,9 @@ part 'pet_service_yaml.swagger.g.dart'; abstract class PetServiceYaml extends ChopperService { static PetServiceYaml create({ ChopperClient? client, + http.Client? httpClient, Authenticator? authenticator, + Converter? converter, Uri? baseUrl, Iterable? interceptors, }) { @@ -34,8 +37,9 @@ abstract class PetServiceYaml extends ChopperService { final newClient = ChopperClient( services: [_$PetServiceYaml()], - converter: $JsonSerializableConverter(), + converter: converter ?? $JsonSerializableConverter(), interceptors: interceptors ?? [], + client: httpClient, authenticator: authenticator, baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); return _$PetServiceYaml(newClient); @@ -45,11 +49,11 @@ abstract class PetServiceYaml extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPost({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPost(body: body, cacheControl: cacheControl); + return _petPost(body: body, cacheControl: cacheControl?.toString()); } ///Add a new pet to the store @@ -64,11 +68,11 @@ abstract class PetServiceYaml extends ChopperService { ///@param body Pet object that needs to be added to the store Future petPut({ required Pet? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petPut(body: body, cacheControl: cacheControl); + return _petPut(body: body, cacheControl: cacheControl?.toString()); } ///Update an existing pet @@ -82,20 +86,21 @@ abstract class PetServiceYaml extends ChopperService { ///Finds Pets by status ///@param status Status values that need to be considered for filter Future>> petFindByStatusGet({ - required enums.PetFindByStatusGetStatus? status, - String? cacheControl, + required List? status, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petFindByStatusGet( - status: status?.value?.toString(), cacheControl: cacheControl); + status: petFindByStatusGetStatusListToJson(status), + cacheControl: cacheControl?.toString()); } ///Finds Pets by status ///@param status Status values that need to be considered for filter @Get(path: '/pet/findByStatus') Future>> _petFindByStatusGet({ - @Query('status') required String? status, + @Query() required List? status, @Header('Cache-Control') String? cacheControl, }); @@ -103,18 +108,19 @@ abstract class PetServiceYaml extends ChopperService { ///@param tags Tags to filter by Future>> petFindByTagsGet({ required List? tags, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - return _petFindByTagsGet(tags: tags, cacheControl: cacheControl); + return _petFindByTagsGet( + tags: tags, cacheControl: cacheControl?.toString()); } ///Finds Pets by tags ///@param tags Tags to filter by @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ - @Query('tags') required List? tags, + @Query() required List? tags, @Header('Cache-Control') String? cacheControl, }); @@ -122,13 +128,15 @@ abstract class PetServiceYaml extends ChopperService { ///@param petId ID of pet to return Future> petPetIdGet({ required int? petId, - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); return _petPetIdGet( - petId: petId, apiKey: apiKey, cacheControl: cacheControl); + petId: petId, + apiKey: apiKey?.toString(), + cacheControl: cacheControl?.toString()); } ///Find pet by ID @@ -148,10 +156,13 @@ abstract class PetServiceYaml extends ChopperService { required int? petId, String? name, String? status, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdPost( - petId: petId, name: name, status: status, cacheControl: cacheControl); + petId: petId, + name: name, + status: status, + cacheControl: cacheControl?.toString()); } ///Updates a pet in the store with form data @@ -175,10 +186,12 @@ abstract class PetServiceYaml extends ChopperService { Future petPetIdDelete({ String? apiKey, required int? petId, - String? cacheControl, + dynamic cacheControl, }) { return _petPetIdDelete( - apiKey: apiKey, petId: petId, cacheControl: cacheControl); + apiKey: apiKey?.toString(), + petId: petId, + cacheControl: cacheControl?.toString()); } ///Deletes a pet @@ -199,7 +212,7 @@ abstract class PetServiceYaml extends ChopperService { required int? petId, String? additionalMetadata, List? file, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent( ApiResponse, () => ApiResponse.fromJsonFactory); @@ -208,7 +221,7 @@ abstract class PetServiceYaml extends ChopperService { petId: petId, additionalMetadata: additionalMetadata, file: file, - cacheControl: cacheControl); + cacheControl: cacheControl?.toString()); } ///uploads an image @@ -228,10 +241,11 @@ abstract class PetServiceYaml extends ChopperService { ///Returns pet inventories by status Future> storeInventoryGet({ - String? apiKey, - String? cacheControl, + dynamic apiKey, + dynamic cacheControl, }) { - return _storeInventoryGet(apiKey: apiKey, cacheControl: cacheControl); + return _storeInventoryGet( + apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); } ///Returns pet inventories by status @@ -245,11 +259,11 @@ abstract class PetServiceYaml extends ChopperService { ///@param body order placed for purchasing the pet Future> storeOrderPost({ required Order? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderPost(body: body, cacheControl: cacheControl); + return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); } ///Place an order for a pet @@ -264,11 +278,12 @@ abstract class PetServiceYaml extends ChopperService { ///@param orderId ID of pet that needs to be fetched Future> storeOrderOrderIdGet({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - return _storeOrderOrderIdGet(orderId: orderId, cacheControl: cacheControl); + return _storeOrderOrderIdGet( + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Find purchase order by ID @@ -283,10 +298,10 @@ abstract class PetServiceYaml extends ChopperService { ///@param orderId ID of the order that needs to be deleted Future storeOrderOrderIdDelete({ required int? orderId, - String? cacheControl, + dynamic cacheControl, }) { return _storeOrderOrderIdDelete( - orderId: orderId, cacheControl: cacheControl); + orderId: orderId, cacheControl: cacheControl?.toString()); } ///Delete purchase order by ID @@ -301,11 +316,11 @@ abstract class PetServiceYaml extends ChopperService { ///@param body Created user object Future userPost({ required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userPost(body: body, cacheControl: cacheControl); + return _userPost(body: body, cacheControl: cacheControl?.toString()); } ///Create user @@ -320,9 +335,10 @@ abstract class PetServiceYaml extends ChopperService { ///@param body List of user object Future userCreateWithArrayPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithArrayPost(body: body, cacheControl: cacheControl); + return _userCreateWithArrayPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -337,9 +353,10 @@ abstract class PetServiceYaml extends ChopperService { ///@param body List of user object Future userCreateWithListPost({ required List? body, - String? cacheControl, + dynamic cacheControl, }) { - return _userCreateWithListPost(body: body, cacheControl: cacheControl); + return _userCreateWithListPost( + body: body, cacheControl: cacheControl?.toString()); } ///Creates list of users with given input array @@ -356,10 +373,12 @@ abstract class PetServiceYaml extends ChopperService { Future> userLoginGet({ required String? username, required String? password, - String? cacheControl, + dynamic cacheControl, }) { return _userLoginGet( - username: username, password: password, cacheControl: cacheControl); + username: username, + password: password, + cacheControl: cacheControl?.toString()); } ///Logs user into the system @@ -367,14 +386,14 @@ abstract class PetServiceYaml extends ChopperService { ///@param password The password for login in clear text @Get(path: '/user/login') Future> _userLoginGet({ - @Query('username') required String? username, - @Query('password') required String? password, + @Query() required String? username, + @Query() required String? password, @Header('Cache-Control') String? cacheControl, }); ///Logs out current logged in user session - Future userLogoutGet({String? cacheControl}) { - return _userLogoutGet(cacheControl: cacheControl); + Future userLogoutGet({dynamic cacheControl}) { + return _userLogoutGet(cacheControl: cacheControl?.toString()); } ///Logs out current logged in user session @@ -386,11 +405,12 @@ abstract class PetServiceYaml extends ChopperService { ///@param username The name that needs to be fetched. Use user1 for testing. Future> userUsernameGet({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - return _userUsernameGet(username: username, cacheControl: cacheControl); + return _userUsernameGet( + username: username, cacheControl: cacheControl?.toString()); } ///Get user by user name @@ -407,12 +427,12 @@ abstract class PetServiceYaml extends ChopperService { Future userUsernamePut({ required String? username, required User? body, - String? cacheControl, + dynamic cacheControl, }) { generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); return _userUsernamePut( - username: username, body: body, cacheControl: cacheControl); + username: username, body: body, cacheControl: cacheControl?.toString()); } ///Updated user @@ -429,9 +449,10 @@ abstract class PetServiceYaml extends ChopperService { ///@param username The name that needs to be deleted Future userUsernameDelete({ required String? username, - String? cacheControl, + dynamic cacheControl, }) { - return _userUsernameDelete(username: username, cacheControl: cacheControl); + return _userUsernameDelete( + username: username, cacheControl: cacheControl?.toString()); } ///Delete user @@ -443,9 +464,113 @@ abstract class PetServiceYaml extends ChopperService { }); } +@JsonSerializable(explicitToJson: true) +class Order { + const Order({ + this.id, + this.petId, + this.quantity, + this.shipDate, + this.status, + this.complete, + }); + + factory Order.fromJson(Map json) => _$OrderFromJson(json); + + static const toJsonFactory = _$OrderToJson; + Map toJson() => _$OrderToJson(this); + + @JsonKey(name: 'id', includeIfNull: false) + final int? id; + @JsonKey(name: 'petId', includeIfNull: false) + final int? petId; + @JsonKey(name: 'quantity', includeIfNull: false) + final int? quantity; + @JsonKey(name: 'shipDate', includeIfNull: false) + final DateTime? shipDate; + @JsonKey( + name: 'status', + includeIfNull: false, + toJson: orderStatusNullableToJson, + fromJson: orderStatusNullableFromJson, + ) + final enums.OrderStatus? status; + @JsonKey(name: 'complete', includeIfNull: false, defaultValue: false) + final bool? complete; + static const fromJsonFactory = _$OrderFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is Order && + (identical(other.id, id) || + const DeepCollectionEquality().equals(other.id, id)) && + (identical(other.petId, petId) || + const DeepCollectionEquality().equals(other.petId, petId)) && + (identical(other.quantity, quantity) || + const DeepCollectionEquality() + .equals(other.quantity, quantity)) && + (identical(other.shipDate, shipDate) || + const DeepCollectionEquality() + .equals(other.shipDate, shipDate)) && + (identical(other.status, status) || + const DeepCollectionEquality().equals(other.status, status)) && + (identical(other.complete, complete) || + const DeepCollectionEquality() + .equals(other.complete, complete))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(id) ^ + const DeepCollectionEquality().hash(petId) ^ + const DeepCollectionEquality().hash(quantity) ^ + const DeepCollectionEquality().hash(shipDate) ^ + const DeepCollectionEquality().hash(status) ^ + const DeepCollectionEquality().hash(complete) ^ + runtimeType.hashCode; +} + +extension $OrderExtension on Order { + Order copyWith( + {int? id, + int? petId, + int? quantity, + DateTime? shipDate, + enums.OrderStatus? status, + bool? complete}) { + return Order( + id: id ?? this.id, + petId: petId ?? this.petId, + quantity: quantity ?? this.quantity, + shipDate: shipDate ?? this.shipDate, + status: status ?? this.status, + complete: complete ?? this.complete); + } + + Order copyWithWrapped( + {Wrapped? id, + Wrapped? petId, + Wrapped? quantity, + Wrapped? shipDate, + Wrapped? status, + Wrapped? complete}) { + return Order( + id: (id != null ? id.value : this.id), + petId: (petId != null ? petId.value : this.petId), + quantity: (quantity != null ? quantity.value : this.quantity), + shipDate: (shipDate != null ? shipDate.value : this.shipDate), + status: (status != null ? status.value : this.status), + complete: (complete != null ? complete.value : this.complete)); + } +} + @JsonSerializable(explicitToJson: true) class Category { - Category({ + const Category({ this.id, this.name, }); @@ -453,13 +578,14 @@ class Category { factory Category.fromJson(Map json) => _$CategoryFromJson(json); + static const toJsonFactory = _$CategoryToJson; + Map toJson() => _$CategoryToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$CategoryFromJson; - static const toJsonFactory = _$CategoryToJson; - Map toJson() => _$CategoryToJson(this); @override bool operator ==(dynamic other) { @@ -482,11 +608,11 @@ class Category { } extension $CategoryExtension on Category { - Category copyWith({num? id, String? name}) { + Category copyWith({int? id, String? name}) { return Category(id: id ?? this.id, name: name ?? this.name); } - Category copyWithWrapped({Wrapped? id, Wrapped? name}) { + Category copyWithWrapped({Wrapped? id, Wrapped? name}) { return Category( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); @@ -495,7 +621,7 @@ extension $CategoryExtension on Category { @JsonSerializable(explicitToJson: true) class User { - User({ + const User({ this.id, this.username, this.firstName, @@ -508,8 +634,11 @@ class User { factory User.fromJson(Map json) => _$UserFromJson(json); + static const toJsonFactory = _$UserToJson; + Map toJson() => _$UserToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') final String? username; @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') @@ -525,8 +654,6 @@ class User { @JsonKey(name: 'userStatus', includeIfNull: false) final int? userStatus; static const fromJsonFactory = _$UserFromJson; - static const toJsonFactory = _$UserToJson; - Map toJson() => _$UserToJson(this); @override bool operator ==(dynamic other) { @@ -573,7 +700,7 @@ class User { extension $UserExtension on User { User copyWith( - {num? id, + {int? id, String? username, String? firstName, String? lastName, @@ -593,7 +720,7 @@ extension $UserExtension on User { } User copyWithWrapped( - {Wrapped? id, + {Wrapped? id, Wrapped? username, Wrapped? firstName, Wrapped? lastName, @@ -615,20 +742,21 @@ extension $UserExtension on User { @JsonSerializable(explicitToJson: true) class Tag { - Tag({ + const Tag({ this.id, this.name, }); factory Tag.fromJson(Map json) => _$TagFromJson(json); + static const toJsonFactory = _$TagToJson; + Map toJson() => _$TagToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') final String? name; static const fromJsonFactory = _$TagFromJson; - static const toJsonFactory = _$TagToJson; - Map toJson() => _$TagToJson(this); @override bool operator ==(dynamic other) { @@ -651,11 +779,11 @@ class Tag { } extension $TagExtension on Tag { - Tag copyWith({num? id, String? name}) { + Tag copyWith({int? id, String? name}) { return Tag(id: id ?? this.id, name: name ?? this.name); } - Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { + Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { return Tag( id: (id != null ? id.value : this.id), name: (name != null ? name.value : this.name)); @@ -664,19 +792,22 @@ extension $TagExtension on Tag { @JsonSerializable(explicitToJson: true) class Pet { - Pet({ + const Pet({ this.id, this.category, - this.name, - this.photoUrls, + required this.name, + required this.photoUrls, this.tags, this.status, }); factory Pet.fromJson(Map json) => _$PetFromJson(json); + static const toJsonFactory = _$PetToJson; + Map toJson() => _$PetToJson(this); + @JsonKey(name: 'id', includeIfNull: false) - final num? id; + final int? id; @JsonKey(name: 'category', includeIfNull: false) final Category? category; @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') @@ -688,13 +819,11 @@ class Pet { @JsonKey( name: 'status', includeIfNull: false, - toJson: petStatusToJson, - fromJson: petStatusFromJson, + toJson: petStatusNullableToJson, + fromJson: petStatusNullableFromJson, ) final enums.PetStatus? status; static const fromJsonFactory = _$PetFromJson; - static const toJsonFactory = _$PetToJson; - Map toJson() => _$PetToJson(this); @override bool operator ==(dynamic other) { @@ -732,7 +861,7 @@ class Pet { extension $PetExtension on Pet { Pet copyWith( - {num? id, + {int? id, Category? category, String? name, List? photoUrls, @@ -748,7 +877,7 @@ extension $PetExtension on Pet { } Pet copyWithWrapped( - {Wrapped? id, + {Wrapped? id, Wrapped? category, Wrapped? name, Wrapped?>? photoUrls, @@ -766,7 +895,7 @@ extension $PetExtension on Pet { @JsonSerializable(explicitToJson: true) class ApiResponse { - ApiResponse({ + const ApiResponse({ this.code, this.type, this.message, @@ -775,6 +904,9 @@ class ApiResponse { factory ApiResponse.fromJson(Map json) => _$ApiResponseFromJson(json); + static const toJsonFactory = _$ApiResponseToJson; + Map toJson() => _$ApiResponseToJson(this); + @JsonKey(name: 'code', includeIfNull: false) final int? code; @JsonKey(name: 'type', includeIfNull: false, defaultValue: '') @@ -782,8 +914,6 @@ class ApiResponse { @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') final String? message; static const fromJsonFactory = _$ApiResponseFromJson; - static const toJsonFactory = _$ApiResponseToJson; - Map toJson() => _$ApiResponseToJson(this); @override bool operator ==(dynamic other) { @@ -827,20 +957,41 @@ extension $ApiResponseExtension on ApiResponse { } } -String? orderStatusToJson(enums.OrderStatus? orderStatus) { +String? orderStatusNullableToJson(enums.OrderStatus? orderStatus) { return orderStatus?.value; } +String? orderStatusToJson(enums.OrderStatus orderStatus) { + return orderStatus.value; +} + enums.OrderStatus orderStatusFromJson( Object? orderStatus, [ enums.OrderStatus? defaultValue, ]) { - return enums.OrderStatus.values - .firstWhereOrNull((e) => e.value == orderStatus) ?? + return enums.OrderStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + orderStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.OrderStatus.swaggerGeneratedUnknown; } +enums.OrderStatus? orderStatusNullableFromJson( + Object? orderStatus, [ + enums.OrderStatus? defaultValue, +]) { + if (orderStatus == null) { + return null; + } + return enums.OrderStatus.values + .firstWhereOrNull((e) => e.value == orderStatus) ?? + defaultValue; +} + +String orderStatusExplodedListToJson(List? orderStatus) { + return orderStatus?.map((e) => e.value!).join(',') ?? ''; +} + List orderStatusListToJson(List? orderStatus) { if (orderStatus == null) { return []; @@ -871,19 +1022,40 @@ List? orderStatusNullableListFromJson( return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); } -String? petStatusToJson(enums.PetStatus? petStatus) { +String? petStatusNullableToJson(enums.PetStatus? petStatus) { return petStatus?.value; } +String? petStatusToJson(enums.PetStatus petStatus) { + return petStatus.value; +} + enums.PetStatus petStatusFromJson( Object? petStatus, [ enums.PetStatus? defaultValue, ]) { - return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + return enums.PetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetStatus.swaggerGeneratedUnknown; } +enums.PetStatus? petStatusNullableFromJson( + Object? petStatus, [ + enums.PetStatus? defaultValue, +]) { + if (petStatus == null) { + return null; + } + return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? + defaultValue; +} + +String petStatusExplodedListToJson(List? petStatus) { + return petStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petStatusListToJson(List? petStatus) { if (petStatus == null) { return []; @@ -914,21 +1086,44 @@ List? petStatusNullableListFromJson( return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); } -String? petFindByStatusGetStatusToJson( +String? petFindByStatusGetStatusNullableToJson( enums.PetFindByStatusGetStatus? petFindByStatusGetStatus) { return petFindByStatusGetStatus?.value; } +String? petFindByStatusGetStatusToJson( + enums.PetFindByStatusGetStatus petFindByStatusGetStatus) { + return petFindByStatusGetStatus.value; +} + enums.PetFindByStatusGetStatus petFindByStatusGetStatusFromJson( Object? petFindByStatusGetStatus, [ enums.PetFindByStatusGetStatus? defaultValue, ]) { - return enums.PetFindByStatusGetStatus.values - .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + return enums.PetFindByStatusGetStatus.values.firstWhereOrNull((e) => + e.value.toString().toLowerCase() == + petFindByStatusGetStatus?.toString().toLowerCase()) ?? defaultValue ?? enums.PetFindByStatusGetStatus.swaggerGeneratedUnknown; } +enums.PetFindByStatusGetStatus? petFindByStatusGetStatusNullableFromJson( + Object? petFindByStatusGetStatus, [ + enums.PetFindByStatusGetStatus? defaultValue, +]) { + if (petFindByStatusGetStatus == null) { + return null; + } + return enums.PetFindByStatusGetStatus.values + .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? + defaultValue; +} + +String petFindByStatusGetStatusExplodedListToJson( + List? petFindByStatusGetStatus) { + return petFindByStatusGetStatus?.map((e) => e.value!).join(',') ?? ''; +} + List petFindByStatusGetStatusListToJson( List? petFindByStatusGetStatus) { if (petFindByStatusGetStatus == null) { @@ -1019,6 +1214,16 @@ class $JsonSerializableConverter extends chopper.JsonConverter { return chopper.Response(response.base, null, error: response.error); } + if (ResultType == String) { + return response.copyWith(); + } + + if (ResultType == DateTime) { + return response.copyWith( + body: DateTime.parse((response.body as String).replaceAll('"', '')) + as ResultType); + } + final jsonRes = await super.convertResponse(response); return jsonRes.copyWith( body: $jsonDecoder.decode(jsonRes.body) as ResultType); diff --git a/example/lib/swagger_generated_code/pet_service_yaml.swagger.g.dart b/example/lib/swagger_generated_code/pet_service_yaml.swagger.g.dart index ce9984c2..d8252e6d 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.swagger.g.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.swagger.g.dart @@ -6,8 +6,37 @@ part of 'pet_service_yaml.swagger.dart'; // JsonSerializableGenerator // ************************************************************************** +Order _$OrderFromJson(Map json) => Order( + id: json['id'] as int?, + petId: json['petId'] as int?, + quantity: json['quantity'] as int?, + shipDate: json['shipDate'] == null + ? null + : DateTime.parse(json['shipDate'] as String), + status: orderStatusNullableFromJson(json['status']), + complete: json['complete'] as bool? ?? false, + ); + +Map _$OrderToJson(Order instance) { + final val = {}; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('id', instance.id); + writeNotNull('petId', instance.petId); + writeNotNull('quantity', instance.quantity); + writeNotNull('shipDate', instance.shipDate?.toIso8601String()); + writeNotNull('status', orderStatusNullableToJson(instance.status)); + writeNotNull('complete', instance.complete); + return val; +} + Category _$CategoryFromJson(Map json) => Category( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -26,7 +55,7 @@ Map _$CategoryToJson(Category instance) { } User _$UserFromJson(Map json) => User( - id: json['id'] as num?, + id: json['id'] as int?, username: json['username'] as String? ?? '', firstName: json['firstName'] as String? ?? '', lastName: json['lastName'] as String? ?? '', @@ -57,7 +86,7 @@ Map _$UserToJson(User instance) { } Tag _$TagFromJson(Map json) => Tag( - id: json['id'] as num?, + id: json['id'] as int?, name: json['name'] as String? ?? '', ); @@ -76,7 +105,7 @@ Map _$TagToJson(Tag instance) { } Pet _$PetFromJson(Map json) => Pet( - id: json['id'] as num?, + id: json['id'] as int?, category: json['category'] == null ? null : Category.fromJson(json['category'] as Map), @@ -87,7 +116,7 @@ Pet _$PetFromJson(Map json) => Pet( tags: (json['tags'] as List?) ?.map((e) => Tag.fromJson(e as Map)) .toList(), - status: petStatusFromJson(json['status']), + status: petStatusNullableFromJson(json['status']), ); Map _$PetToJson(Pet instance) { @@ -104,7 +133,7 @@ Map _$PetToJson(Pet instance) { writeNotNull('name', instance.name); writeNotNull('photoUrls', instance.photoUrls); writeNotNull('tags', instance.tags?.map((e) => e.toJson()).toList()); - writeNotNull('status', petStatusToJson(instance.status)); + writeNotNull('status', petStatusNullableToJson(instance.status)); return val; } diff --git a/lib/src/code_generators/swagger_additions_generator.dart b/lib/src/code_generators/swagger_additions_generator.dart index 601a0c6d..834a28a6 100644 --- a/lib/src/code_generators/swagger_additions_generator.dart +++ b/lib/src/code_generators/swagger_additions_generator.dart @@ -49,8 +49,9 @@ class SwaggerAdditionsGenerator extends SwaggerGeneratorBase { final chopperPartImport = buildOnlyModels ? '' : "part '$swaggerFileName.swagger.chopper.dart';"; - final overridenModels = options.overridenModels.containsKey(swaggerFileName) - ? 'import \'${swaggerFileName}_overriden.dart\';' + final overridenModels = options.overridenModels + .any((e) => e.fileName == swaggerFileName) + ? 'import \'${options.overridenModels.firstWhere((e) => e.fileName == swaggerFileName).importUrl}\';' : ''; final chopperImports = buildOnlyModels diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 383e987e..6795e3be 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -40,8 +40,10 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { Map allClasses, String fileName, ) { - if (options.overridenModels[fileName] - ?.contains(getValidatedClassName(className)) == + if (options.overridenModels + .firstWhereOrNull((e) => e.fileName == fileName) + ?.overridenModels + .contains(getValidatedClassName(className)) == true) { return ''; } @@ -104,8 +106,10 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final itemClassName = '$className\$Item'; - if (options.overridenModels[fileName] - ?.contains(getValidatedClassName(itemClassName)) == + if (options.overridenModels + .firstWhereOrNull((e) => e.fileName == fileName) + ?.overridenModels + .contains(getValidatedClassName(itemClassName)) == true) { return ''; } @@ -292,7 +296,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (classes['enum'] != null) { return ''; } - + final currentClass = classes[className]!; return generateModelClassContent( diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 394735d1..f5529d1b 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -34,7 +34,7 @@ class GeneratorOptions { this.overrideEqualsAndHashcode = true, this.overrideToString = true, this.pageWidth, - this.overridenModels = const {}, + this.overridenModels = const [], this.generateToJsonFor = const [], this.multipartFileType = 'List', }); @@ -67,8 +67,8 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool withConverter; - @JsonKey(defaultValue: {}) - final Map> overridenModels; + @JsonKey(defaultValue: []) + final List overridenModels; @JsonKey(defaultValue: []) final List generateToJsonFor; @@ -195,3 +195,24 @@ class DefaultHeaderValueMap { factory DefaultHeaderValueMap.fromJson(Map json) => _$DefaultHeaderValueMapFromJson(json); } + +@JsonSerializable(fieldRename: FieldRename.snake) +class OverridenModelsItem { + @JsonKey() + final String fileName; + @JsonKey() + final List overridenModels; + @JsonKey() + final String importUrl; + + OverridenModelsItem({ + required this.fileName, + required this.overridenModels, + required this.importUrl, + }); + + Map toJson() => _$OverridenModelsItemToJson(this); + + factory OverridenModelsItem.fromJson(Map json) => + _$OverridenModelsItemFromJson(json); +} diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 5ced0d8a..477b1347 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -75,11 +75,11 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( json['override_equals_and_hashcode'] as bool? ?? true, overrideToString: json['override_to_string'] as bool? ?? true, pageWidth: json['page_width'] as int?, - overridenModels: (json['overriden_models'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, + overridenModels: (json['overriden_models'] as List?) + ?.map((e) => OverridenModelsItem.fromJson( + Map.from(e as Map))) + .toList() ?? + [], generateToJsonFor: (json['generate_to_json_for'] as List?) ?.map((e) => e as String) .toList() ?? @@ -164,3 +164,20 @@ Map _$DefaultHeaderValueMapToJson( 'header_name': instance.headerName, 'default_value': instance.defaultValue, }; + +OverridenModelsItem _$OverridenModelsItemFromJson(Map json) => + OverridenModelsItem( + fileName: json['file_name'] as String, + overridenModels: (json['overriden_models'] as List) + .map((e) => e as String) + .toList(), + importUrl: json['import_url'] as String, + ); + +Map _$OverridenModelsItemToJson( + OverridenModelsItem instance) => + { + 'file_name': instance.fileName, + 'overriden_models': instance.overridenModels, + 'import_url': instance.importUrl, + }; diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index 76997f7d..dba7e1ad 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -63,22 +63,6 @@ Map> _generateExtensions(GeneratorOptions options) { additionalResultPath = _getAdditionalResultPath(options).replaceAll('\\', '/'); - if (options.overridenModels.isNotEmpty) { - for (final fileName in options.overridenModels.keys) { - final path = normalize('${options.outputFolder}${fileName}_overriden.dart'); - - if (!Directory(options.outputFolder).existsSync()) { - Directory(options.outputFolder).createSync(); - } - - if (!File(path).existsSync()) { - File(path).createSync(); - File(path).writeAsString( - '//Put your overriden models here (${options.overridenModels[fileName]?.join(',')})'); - } - } - } - File(additionalResultPath).createSync(); var out = normalize(options.outputFolder); From cbcc034d4931f9120b7d903a959e055e6d08eeaf Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 15:56:49 +0300 Subject: [PATCH 55/67] Fixed tests --- test/generator_tests/models_generator_test.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index 852c6d5e..c93d4190 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -221,6 +221,7 @@ void main() { [], [], {}, + 'fle_name', ); expect(result, contains(classExpectedResult)); @@ -243,6 +244,7 @@ void main() { [], [], {}, + 'fle_name', ); expect(result, contains(classExpectedResult)); From 1a20bf3271182289444dab3dbc4d0c7eebe1a517 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 16:08:15 +0300 Subject: [PATCH 56/67] Updated pubspec and changelog --- CHANGELOG.md | 5 +++++ pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc9e7690..7113cacf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.13.1 + +* ***Breaking*** Changed Overriden Models usage ([#550](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/550)) +* Fixed generation of allOf request bodies ([#680](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/680)) + # 2.12.2 * Fixed generation of `nullable` and `required` fields ([#650](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/650)) diff --git a/pubspec.yaml b/pubspec.yaml index 44a11b7e..e0e56d8b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.12.2 +version: 2.13.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 70a6665c209fcbafe3e65a1a2792dfdf93f9ac18 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 22 Nov 2023 16:45:25 +0300 Subject: [PATCH 57/67] Removed support of exploded parameters --- lib/src/code_generators/constants.dart | 1 - .../swagger_requests_generator.dart | 21 ++----------------- .../requests/swagger_request_parameter.dart | 4 ---- .../swagger_request_parameter.g2.dart | 2 -- 4 files changed, 2 insertions(+), 26 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 8b0a672b..bb58484b 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -89,7 +89,6 @@ const kArray = 'array'; const kEnum = 'enum'; const kBody = 'body'; const kQuery = 'query'; -const kExplodedQuery ='ExplodedQuery'; const kPartFile = 'partFile'; const kPart = 'part'; diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index b1e5b81f..73e3ae75 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -390,13 +390,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } } - if (p.annotations.first.code - .toString() - .contains('symbol=ExplodedQuery')) { - result = result.copyWith( - annotations: [refer('Query()')], type: Reference('String?')); - } - return result; }); @@ -434,11 +427,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { List allModels, ) { final parametersListString = parameters.map((p) { - final isExposed = p.annotations.firstOrNull?.code - .toString() - .contains('symbol=ExplodedQuery') ?? - false; - if (p.type!.symbol!.startsWith('enums.')) { return '${p.name} : ${p.name}?.value?.toString()'; } @@ -457,11 +445,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final typeName = p.type!.symbol!; final name = typeName.substring(11, typeName.length - 2).camelCase; - if (isExposed) { - return '${p.name} : ${name}ExplodedListToJson(${p.name})'; - } else { - return '${p.name} : ${name}ListToJson(${p.name})'; - } + return '${p.name} : ${name}ListToJson(${p.name})'; } return '${p.name} : ${p.name}'; @@ -548,8 +532,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { case kBody: return refer(kBody.pascalCase).call([]); case kQuery: - return refer(parameter.explode ? kExplodedQuery : kQuery.pascalCase) - .call([]); + return refer(kQuery.pascalCase).call([]); default: //https://github.com/lejard-h/chopper/issues/295 return refer(parameter.inParameter.pascalCase) diff --git a/lib/src/swagger_models/requests/swagger_request_parameter.dart b/lib/src/swagger_models/requests/swagger_request_parameter.dart index ae421320..f0c50d59 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.dart @@ -19,7 +19,6 @@ class SwaggerRequestParameter { this.schema, this.ref = '', this.key = '', - this.explode = false, this.enumValuesObj = const [], }); @@ -29,9 +28,6 @@ class SwaggerRequestParameter { @JsonKey(name: 'name', defaultValue: '') String name; - @JsonKey(name: 'explode', defaultValue: false) - bool explode; - @JsonKey(name: 'description', defaultValue: '') String description; diff --git a/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart b/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart index 860bd5f2..ba9e136e 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart @@ -27,14 +27,12 @@ SwaggerRequestParameter _$SwaggerRequestParameterFromJson( ref: json[r'$ref'] as String? ?? '', key: json['key'] as String? ?? '', enumValuesObj: json['enum'] as List? ?? [], - explode: json['explode'] as bool? ?? false, ); Map _$SwaggerRequestParameterToJson( SwaggerRequestParameter instance) => { 'in': instance.inParameter, - 'explode': instance.explode, 'name': instance.name, 'description': instance.description, 'required': instance.isRequired, From a1fb0e5cf6b65ab555b854a936120b00717261cb Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 12:42:06 +0300 Subject: [PATCH 58/67] Fixed generation of patameters contains keywords --- lib/src/code_generators/swagger_requests_generator.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 73e3ae75..563ddd9b 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -531,8 +531,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { .call([literalString(parameter.name.replaceAll('\$', ''))]); case kBody: return refer(kBody.pascalCase).call([]); - case kQuery: - return refer(kQuery.pascalCase).call([]); default: //https://github.com/lejard-h/chopper/issues/295 return refer(parameter.inParameter.pascalCase) From 29a517cd8c4838ce12648100ed56404d690d0ec1 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 12:48:15 +0300 Subject: [PATCH 59/67] Updated pubspec and changelog --- CHANGELOG.md | 4 ++++ pubspec.yaml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7113cacf..7d12e0b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.13.2 + +* Fixed generation key word parameter names ([#685](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/685)) + # 2.13.1 * ***Breaking*** Changed Overriden Models usage ([#550](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/550)) diff --git a/pubspec.yaml b/pubspec.yaml index e0e56d8b..a119827f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.13.1 +version: 2.13.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 0e1e1108a4aea5079390d3da99e2b80c580af04c Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 13:12:24 +0300 Subject: [PATCH 60/67] Fixed generation of nullable and not nullable fields --- lib/src/code_generators/swagger_models_generator.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 6795e3be..29dafe98 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -781,7 +781,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final isPropertyNullable = options.nullableModels.contains(className) || refSchema?.isNullable == true || - !requiredProperties.contains(propertyName); + !requiredProperties.contains(propertyKey); final unknownEnumValue = generateEnumValue( allEnumNames: allEnumNames, From 41b4fbd8037475f09f306acb25180ad6451ee70c Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 14:35:23 +0300 Subject: [PATCH 61/67] Fixed generation of list parameters with specific names --- lib/src/code_generators/swagger_models_generator.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 29dafe98..b30603f2 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -378,7 +378,9 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } if (parameter.items?.properties.isNotEmpty == true) { - return 'List<${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}\$Item$modelPostfix>'; + final parameterNameCombination = + '${getValidatedClassName(className)}\$${getValidatedClassName(parameterName)}\$Item$modelPostfix'; + return 'List<${getValidatedClassName(parameterNameCombination)}>'; } if (parameter.hasRef) { From d103118975e7f66ec2cbf10a1f9d28ef935be6eb Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 15:24:35 +0300 Subject: [PATCH 62/67] Fixed formurlencoded requests --- .../swagger_requests_generator.dart | 157 +++++++++++------- .../requests/swagger_request.dart | 12 +- 2 files changed, 108 insertions(+), 61 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 563ddd9b..12ff685a 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -189,6 +189,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ['post', 'put', 'patch'].contains(requestType) && swaggerRequest.parameters.none((p) => p.inParameter == kBody); + final isFormUrlEncoded = + swaggerRequest.requestBody?.content?.isFormUrlEncoded ?? false; + final isMultipart = parameters.any((p) { return p.annotations .any((p0) => p0.call([]).toString().contains('symbol=Part')); @@ -208,7 +211,12 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { )) ..name = methodName ..annotations.addAll(_getMethodAnnotation( - requestType, annotationPath, hasOptionalBody, isMultipart)) + requestType, + annotationPath, + hasOptionalBody, + isMultipart, + isFormUrlEncoded, + )) ..returns = Reference(returns)); final allModels = _getAllMethodModels( @@ -468,7 +476,23 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { String path, bool hasOptionalBody, bool isMultipart, + bool isFormUrlEncoded, ) { + if (isFormUrlEncoded) { + return [ + refer(requestType.pascalCase).call( + [], + { + kPath: literalString(path), + 'headers': refer('{contentTypeKey: formEncodedHeaders}'), + }, + ), + refer('FactoryConverter').call( + [refer('request: FormUrlEncodedConverter.requestFactory')], + {}, + ), + ]; + } return [ refer(requestType.pascalCase).call( [], @@ -767,8 +791,23 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final requestBody = swaggerRequest.requestBody; if (requestBody != null) { - // MULTIPART REQUESTS - if (requestBody.content?.isMultipart == true) { + // FORM URLENCODED + if (requestBody.content?.isFormUrlEncoded == true) { + result.add( + Parameter( + (p) => p + ..name = kBody + ..named = true + ..required = true + ..type = Reference(kMapStringDynamic) + ..named = true + ..annotations.add( + refer(kPart.pascalCase).call([]), + ), + ), + ); + } else if (requestBody.content?.isMultipart == true) { + // MULTIPART REQUESTS var schema = requestBody.content?.schema; if (schema?.ref.isNotEmpty == true) { @@ -864,70 +903,70 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }); return result.distinctParameters(); - } + } else { +// OTHER REQUESTS EXCEPT MULTIPART + var typeName = ''; + + if (requestBody.hasRef) { + final ref = requestBody.ref; + typeName = ref.getRef(); + + if (root.components?.requestBodies + .containsKey(ref.getUnformattedRef()) == + true) { + typeName = getValidatedClassName( + '${ref.getUnformattedRef()}\$RequestBody'); + } - // OTHER REQUESTS EXCEPT MULTIPART - var typeName = ''; + final requestBodyRef = + root.components?.requestBodies[ref.getRef()]?.ref ?? ''; - if (requestBody.hasRef) { - final ref = requestBody.ref; - typeName = ref.getRef(); + if (requestBodyRef.isNotEmpty) { + typeName = requestBodyRef.getRef(); + } - if (root.components?.requestBodies - .containsKey(ref.getUnformattedRef()) == - true) { - typeName = - getValidatedClassName('${ref.getUnformattedRef()}\$RequestBody'); + typeName = getValidatedClassName(typeName); } - final requestBodyRef = - root.components?.requestBodies[ref.getRef()]?.ref ?? ''; - - if (requestBodyRef.isNotEmpty) { - typeName = requestBodyRef.getRef(); + final schema = requestBody.content?.schema; + + if (schema != null) { + if (schema.format == kBinary || schema.oneOf.isNotEmpty) { + typeName = kObject.pascalCase; + } else if (schema.items?.type.isNotEmpty == true) { + typeName = _mapParameterName(schema.items!.type, + schema.items!.format, options.modelPostfix) + .asList(); + } else if (schema.allOf.length == 1 && + schema.allOf.first.ref.isNotEmpty) { + typeName = getValidatedClassName(schema.allOf.first.ref.getRef()); + } else { + typeName = _getRequestBodyTypeName( + schema: schema, + modelPostfix: options.modelPostfix, + root: root, + requestPath: path + requestType.pascalCase, + ); + } } - typeName = getValidatedClassName(typeName); - } - - final schema = requestBody.content?.schema; - - if (schema != null) { - if (schema.format == kBinary || schema.oneOf.isNotEmpty) { - typeName = kObject.pascalCase; - } else if (schema.items?.type.isNotEmpty == true) { - typeName = _mapParameterName(schema.items!.type, schema.items!.format, - options.modelPostfix) - .asList(); - } else if (schema.allOf.length == 1 && - schema.allOf.first.ref.isNotEmpty) { - typeName = getValidatedClassName(schema.allOf.first.ref.getRef()); - } else { - typeName = _getRequestBodyTypeName( - schema: schema, - modelPostfix: options.modelPostfix, - root: root, - requestPath: path + requestType.pascalCase, - ); - } + result.add( + Parameter( + (p) => p + ..name = kBody + ..named = true + ..required = true + ..type = Reference( + (typeName.isNotEmpty ? typeName : kObject.pascalCase) + .makeNullable(), + ) + ..named = true + ..annotations.add( + refer(kBody.pascalCase).call([]), + ), + ), + ); } - - result.add( - Parameter( - (p) => p - ..name = kBody - ..named = true - ..required = true - ..type = Reference( - (typeName.isNotEmpty ? typeName : kObject.pascalCase) - .makeNullable(), - ) - ..named = true - ..annotations.add( - refer(kBody.pascalCase).call([]), - ), - ), - ); } return result.distinctParameters(); diff --git a/lib/src/swagger_models/requests/swagger_request.dart b/lib/src/swagger_models/requests/swagger_request.dart index cabdd228..6c2baecf 100644 --- a/lib/src/swagger_models/requests/swagger_request.dart +++ b/lib/src/swagger_models/requests/swagger_request.dart @@ -85,7 +85,9 @@ RequestContent? _contentFromJson(Map? map) { final multipart = map['multipart/form-data']['schema'] as Map; return RequestContent( - isMultipart: true, schema: SwaggerSchema.fromJson(multipart)); + isFormUrlEncoded: true, + schema: SwaggerSchema.fromJson(multipart), + ); } if (map.containsKey('application/x-www-form-urlencoded') && @@ -94,7 +96,10 @@ RequestContent? _contentFromJson(Map? map) { final multipart = map['application/x-www-form-urlencoded']['schema'] as Map; return RequestContent( - isMultipart: true, schema: SwaggerSchema.fromJson(multipart)); + isMultipart: true, + isFormUrlEncoded: true, + schema: SwaggerSchema.fromJson(multipart), + ); } final content = map.values.first as Map; @@ -106,12 +111,15 @@ RequestContent? _contentFromJson(Map? map) { class RequestContent { RequestContent({ this.isMultipart, + this.isFormUrlEncoded = false, this.schema, }); @JsonKey(name: 'schema') final SwaggerSchema? schema; + final bool isFormUrlEncoded; + final bool? isMultipart; Map toJson() => _$RequestContentToJson(this); From 6a433b7a4808869f5abcfd7da52de67cec2699d6 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 1 Dec 2023 15:25:32 +0300 Subject: [PATCH 63/67] Revert "Fixed formurlencoded requests" This reverts commit d103118975e7f66ec2cbf10a1f9d28ef935be6eb. --- .../swagger_requests_generator.dart | 157 +++++++----------- .../requests/swagger_request.dart | 12 +- 2 files changed, 61 insertions(+), 108 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 12ff685a..563ddd9b 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -189,9 +189,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ['post', 'put', 'patch'].contains(requestType) && swaggerRequest.parameters.none((p) => p.inParameter == kBody); - final isFormUrlEncoded = - swaggerRequest.requestBody?.content?.isFormUrlEncoded ?? false; - final isMultipart = parameters.any((p) { return p.annotations .any((p0) => p0.call([]).toString().contains('symbol=Part')); @@ -211,12 +208,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { )) ..name = methodName ..annotations.addAll(_getMethodAnnotation( - requestType, - annotationPath, - hasOptionalBody, - isMultipart, - isFormUrlEncoded, - )) + requestType, annotationPath, hasOptionalBody, isMultipart)) ..returns = Reference(returns)); final allModels = _getAllMethodModels( @@ -476,23 +468,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { String path, bool hasOptionalBody, bool isMultipart, - bool isFormUrlEncoded, ) { - if (isFormUrlEncoded) { - return [ - refer(requestType.pascalCase).call( - [], - { - kPath: literalString(path), - 'headers': refer('{contentTypeKey: formEncodedHeaders}'), - }, - ), - refer('FactoryConverter').call( - [refer('request: FormUrlEncodedConverter.requestFactory')], - {}, - ), - ]; - } return [ refer(requestType.pascalCase).call( [], @@ -791,23 +767,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final requestBody = swaggerRequest.requestBody; if (requestBody != null) { - // FORM URLENCODED - if (requestBody.content?.isFormUrlEncoded == true) { - result.add( - Parameter( - (p) => p - ..name = kBody - ..named = true - ..required = true - ..type = Reference(kMapStringDynamic) - ..named = true - ..annotations.add( - refer(kPart.pascalCase).call([]), - ), - ), - ); - } else if (requestBody.content?.isMultipart == true) { - // MULTIPART REQUESTS + // MULTIPART REQUESTS + if (requestBody.content?.isMultipart == true) { var schema = requestBody.content?.schema; if (schema?.ref.isNotEmpty == true) { @@ -903,70 +864,70 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }); return result.distinctParameters(); - } else { -// OTHER REQUESTS EXCEPT MULTIPART - var typeName = ''; - - if (requestBody.hasRef) { - final ref = requestBody.ref; - typeName = ref.getRef(); - - if (root.components?.requestBodies - .containsKey(ref.getUnformattedRef()) == - true) { - typeName = getValidatedClassName( - '${ref.getUnformattedRef()}\$RequestBody'); - } + } - final requestBodyRef = - root.components?.requestBodies[ref.getRef()]?.ref ?? ''; + // OTHER REQUESTS EXCEPT MULTIPART + var typeName = ''; - if (requestBodyRef.isNotEmpty) { - typeName = requestBodyRef.getRef(); - } + if (requestBody.hasRef) { + final ref = requestBody.ref; + typeName = ref.getRef(); - typeName = getValidatedClassName(typeName); + if (root.components?.requestBodies + .containsKey(ref.getUnformattedRef()) == + true) { + typeName = + getValidatedClassName('${ref.getUnformattedRef()}\$RequestBody'); } - final schema = requestBody.content?.schema; - - if (schema != null) { - if (schema.format == kBinary || schema.oneOf.isNotEmpty) { - typeName = kObject.pascalCase; - } else if (schema.items?.type.isNotEmpty == true) { - typeName = _mapParameterName(schema.items!.type, - schema.items!.format, options.modelPostfix) - .asList(); - } else if (schema.allOf.length == 1 && - schema.allOf.first.ref.isNotEmpty) { - typeName = getValidatedClassName(schema.allOf.first.ref.getRef()); - } else { - typeName = _getRequestBodyTypeName( - schema: schema, - modelPostfix: options.modelPostfix, - root: root, - requestPath: path + requestType.pascalCase, - ); - } + final requestBodyRef = + root.components?.requestBodies[ref.getRef()]?.ref ?? ''; + + if (requestBodyRef.isNotEmpty) { + typeName = requestBodyRef.getRef(); } - result.add( - Parameter( - (p) => p - ..name = kBody - ..named = true - ..required = true - ..type = Reference( - (typeName.isNotEmpty ? typeName : kObject.pascalCase) - .makeNullable(), - ) - ..named = true - ..annotations.add( - refer(kBody.pascalCase).call([]), - ), - ), - ); + typeName = getValidatedClassName(typeName); + } + + final schema = requestBody.content?.schema; + + if (schema != null) { + if (schema.format == kBinary || schema.oneOf.isNotEmpty) { + typeName = kObject.pascalCase; + } else if (schema.items?.type.isNotEmpty == true) { + typeName = _mapParameterName(schema.items!.type, schema.items!.format, + options.modelPostfix) + .asList(); + } else if (schema.allOf.length == 1 && + schema.allOf.first.ref.isNotEmpty) { + typeName = getValidatedClassName(schema.allOf.first.ref.getRef()); + } else { + typeName = _getRequestBodyTypeName( + schema: schema, + modelPostfix: options.modelPostfix, + root: root, + requestPath: path + requestType.pascalCase, + ); + } } + + result.add( + Parameter( + (p) => p + ..name = kBody + ..named = true + ..required = true + ..type = Reference( + (typeName.isNotEmpty ? typeName : kObject.pascalCase) + .makeNullable(), + ) + ..named = true + ..annotations.add( + refer(kBody.pascalCase).call([]), + ), + ), + ); } return result.distinctParameters(); diff --git a/lib/src/swagger_models/requests/swagger_request.dart b/lib/src/swagger_models/requests/swagger_request.dart index 6c2baecf..cabdd228 100644 --- a/lib/src/swagger_models/requests/swagger_request.dart +++ b/lib/src/swagger_models/requests/swagger_request.dart @@ -85,9 +85,7 @@ RequestContent? _contentFromJson(Map? map) { final multipart = map['multipart/form-data']['schema'] as Map; return RequestContent( - isFormUrlEncoded: true, - schema: SwaggerSchema.fromJson(multipart), - ); + isMultipart: true, schema: SwaggerSchema.fromJson(multipart)); } if (map.containsKey('application/x-www-form-urlencoded') && @@ -96,10 +94,7 @@ RequestContent? _contentFromJson(Map? map) { final multipart = map['application/x-www-form-urlencoded']['schema'] as Map; return RequestContent( - isMultipart: true, - isFormUrlEncoded: true, - schema: SwaggerSchema.fromJson(multipart), - ); + isMultipart: true, schema: SwaggerSchema.fromJson(multipart)); } final content = map.values.first as Map; @@ -111,15 +106,12 @@ RequestContent? _contentFromJson(Map? map) { class RequestContent { RequestContent({ this.isMultipart, - this.isFormUrlEncoded = false, this.schema, }); @JsonKey(name: 'schema') final SwaggerSchema? schema; - final bool isFormUrlEncoded; - final bool? isMultipart; Map toJson() => _$RequestContentToJson(this); From a472fa4cd17b2a074cb51562a544def02bcc821e Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 8 Dec 2023 14:05:41 +0300 Subject: [PATCH 64/67] 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 a462b41c..de586990 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 2.13.2 +* Some fixes and improvements + +# 2.13.2 + * Fixed generation key word parameter names ([#685](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/685)) diff --git a/pubspec.yaml b/pubspec.yaml index a119827f..b2b38e7e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.13.2 +version: 2.13.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 8e7a9a1bec680de56a7760483a0c1ff60a9ab758 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 8 Dec 2023 14:13:35 +0300 Subject: [PATCH 65/67] formatted code --- lib/src/code_generators/swagger_requests_generator.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index dc33b125..c9ff9da0 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -195,8 +195,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }); final isUrlencoded = parameters.any((p) => - p.type != null && - p.type!.symbol == options.urlencodedFileType); + p.type != null && p.type!.symbol == options.urlencodedFileType); var annotationPath = path; if (options.addBasePathToRequests) { From d464b6822940396f0575cbe6f7e21ceaf2a01317 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 8 Dec 2023 14:14:10 +0300 Subject: [PATCH 66/67] Fixed version in changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de586990..87e38276 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# 2.13.2 +# 2.13.3 * Some fixes and improvements From f07c5c5e652a2310aab7ee505a6b17db37782564 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 15 Dec 2023 13:35:11 +0300 Subject: [PATCH 67/67] Added generation of writeOnly and readOnly fields as nullable and no required (Issue 487) --- .../swagger_models_generator.dart | 30 +++++++++---------- .../responses/swagger_schema.dart | 10 +++++++ .../responses/swagger_schema.g2.dart | 4 +++ 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index b30603f2..24f385b6 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -471,8 +471,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final includeIfNullString = generateIncludeIfNullString(); if (typeName != kDynamic && - (prop.isNullable == true || - options.nullableModels.contains(typeName))) { + (prop.shouldBeNullable || options.nullableModels.contains(typeName))) { typeName = typeName.makeNullable(); } @@ -488,6 +487,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final jsonKeyContent = "@JsonKey(name: '$propertyKey'$includeIfNullString$dateToJsonValue${unknownEnumValue.jsonKey})\n"; + return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } @@ -598,7 +598,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String propertyKey, SwaggerSchema prop, ) { - return prop.isNullable == true || + return prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey); } @@ -667,8 +667,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - if ((prop.isNullable == true || - options.nullableModels.contains(className)) && + if ((prop.shouldBeNullable || options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -734,7 +733,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if (prop.isNullable == true || + if (prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); @@ -782,7 +781,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr } final isPropertyNullable = options.nullableModels.contains(className) || - refSchema?.isNullable == true || + refSchema?.shouldBeNullable == true || !requiredProperties.contains(propertyKey); final unknownEnumValue = generateEnumValue( @@ -805,15 +804,14 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if ((prop.isNullable == true || - options.nullableModels.contains(className)) && + if ((prop.shouldBeNullable || options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } final propertySchema = allClasses[prop.ref.getUnformattedRef()]; - if (propertySchema?.isNullable == true || + if (propertySchema?.shouldBeNullable == true || isPropertyNullable || options.nullableModels.contains(className)) { typeName = typeName.makeNullable(); @@ -855,8 +853,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var enumPropertyName = className.capitalize + key.capitalize; - if ((prop.isNullable == true || - options.nullableModels.contains(className)) && + if ((prop.shouldBeNullable || options.nullableModels.contains(className)) && !requiredProperties.contains(propertyKey)) { enumPropertyName = enumPropertyName.makeNullable(); } @@ -1006,7 +1003,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr var listPropertyName = 'List<$typeName>'; - if (prop.isNullable == true || + if (prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { listPropertyName = listPropertyName.makeNullable(); @@ -1079,7 +1076,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += ')\n'; } - if (prop.isNullable == true || + if (prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); @@ -1341,10 +1338,11 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr propertyNames.add(fieldName); final isNullableProperty = options.nullableModels.contains(className) || - value.isNullable == true || + value.shouldBeNullable || !requiredProperties.contains(key); - final isRequiredProperty = requiredProperties.contains(key); + final isRequiredProperty = + !value.shouldBeNullable && requiredProperties.contains(key); if (isRequiredProperty || !isNullableProperty) { results += '\t\t$kRequired this.$fieldName,\n'; diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index d086bbc0..5f91fb72 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -25,8 +25,16 @@ class SwaggerSchema { this.hasAdditionalProperties = false, this.msEnum, this.title = '', + this.readOnly = false, + this.writeOnly = false, }); + @JsonKey(name: 'readOnly', defaultValue: false) + bool readOnly; + + @JsonKey(name: 'writeOnly', defaultValue: false) + bool writeOnly; + @JsonKey(name: 'type', defaultValue: '') String type; @@ -83,6 +91,8 @@ class SwaggerSchema { @JsonKey(name: 'nullable', defaultValue: null) bool? isNullable; + bool get shouldBeNullable => isNullable == true || readOnly || writeOnly; + @JsonKey(name: 'schema') SwaggerSchema? schema; diff --git a/lib/src/swagger_models/responses/swagger_schema.g2.dart b/lib/src/swagger_models/responses/swagger_schema.g2.dart index aa58c84e..deb0075f 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g2.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g2.dart @@ -42,6 +42,8 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => : _requiredFromJson(json['required']), description: json['description'] as String? ?? '', title: json['title'] as String? ?? '', + readOnly: json['readOnly'] as bool? ?? false, + writeOnly: json['writeOnly'] as bool? ?? false, enumNames: (json['enumNames'] as List?) ?.map((e) => e as String) .toList(), @@ -73,6 +75,8 @@ Map _$SwaggerSchemaToJson(SwaggerSchema instance) => 'anyOf': instance.anyOf, 'allOf': instance.allOf, 'title': instance.title, + 'readOnly': instance.readOnly, + 'writeOnly': instance.writeOnly, 'additionalProperties': instance.hasAdditionalProperties, 'enumNames': instance.enumNames, };