From 2c826d80e5e0f73e192dca73d89f34c61621c937 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 7 Jun 2023 14:18:20 +0300 Subject: [PATCH 01/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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/93] 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, }; From 7992d75f5fff72eaaba6560cbbe4c054b80f9b78 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 15 Dec 2023 13:49:26 +0300 Subject: [PATCH 68/93] Fixed generatino of DateTime query parameters (Issue 536) --- lib/src/code_generators/swagger_requests_generator.dart | 6 +++++- .../swagger_models/requests/swagger_request_parameter.dart | 4 ++++ .../requests/swagger_request_parameter.g2.dart | 2 ++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index c9ff9da0..0dac8e80 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -592,7 +592,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required List allEnums, required Map definedParameters, }) { - final format = parameter.schema?.format ?? ''; + final format = parameter.format ?? parameter.schema?.format ?? ''; if (parameter.items?.enumValues.isNotEmpty == true || parameter.schema?.enumValues.isNotEmpty == true || @@ -691,6 +691,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } String _mapParameterName(String name, String format, String modelPostfix) { + if (name == kString && format == kDateTimeFormat) { + return kDateTimeType; + } + if (name == kArray) { return 'List?'; } diff --git a/lib/src/swagger_models/requests/swagger_request_parameter.dart b/lib/src/swagger_models/requests/swagger_request_parameter.dart index f0c50d59..0b842126 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.dart @@ -20,11 +20,15 @@ class SwaggerRequestParameter { this.ref = '', this.key = '', this.enumValuesObj = const [], + this.format, }); @JsonKey(name: 'in', defaultValue: '') String inParameter; + @JsonKey(name: 'format', defaultValue: null) + String? format; + @JsonKey(name: 'name', defaultValue: '') String name; 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 ba9e136e..a88763f8 100644 --- a/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request_parameter.g2.dart @@ -12,6 +12,7 @@ SwaggerRequestParameter _$SwaggerRequestParameterFromJson( inParameter: json['in'] as String? ?? '', name: json['name'] as String? ?? '', description: json['description'] as String? ?? '', + format: json['format'] as String? ?? null, isRequired: json['required'] as bool? ?? false, type: json['type'] as String? ?? '', item: json['item'] == null @@ -35,6 +36,7 @@ Map _$SwaggerRequestParameterToJson( 'in': instance.inParameter, 'name': instance.name, 'description': instance.description, + 'format': instance.format, 'required': instance.isRequired, r'$ref': instance.ref, 'type': instance.type, From e86556cb2ac387d87cad4138bed8379d2cbdd17d Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 15 Dec 2023 13:52:03 +0300 Subject: [PATCH 69/93] 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 87e38276..f9505abd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.13.4 + +* Make `readOnly` and `writeOnly` fields as `nullable` and `not required` ([#487](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/487)) +* Added support of `DateTime` query parameters ([#694](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/694)) + # 2.13.3 * Some fixes and improvements diff --git a/pubspec.yaml b/pubspec.yaml index b2b38e7e..ec174a72 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.13.3 +version: 2.13.4 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From de96f5e339a07e6adfccf53ba916f280daf9641e Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 15 Dec 2023 14:58:00 +0300 Subject: [PATCH 70/93] Fixed generation in some cases --- lib/src/code_generators/swagger_models_generator.dart | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 24f385b6..6dce5ec8 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -667,8 +667,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - if ((prop.shouldBeNullable || options.nullableModels.contains(className)) && - !requiredProperties.contains(propertyKey)) { + if (prop.shouldBeNullable || + (options.nullableModels.contains(className) && + !requiredProperties.contains(propertyKey))) { typeName = typeName.makeNullable(); } @@ -780,7 +781,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName += options.modelPostfix; } - final isPropertyNullable = options.nullableModels.contains(className) || + final isPropertyNullable = prop.shouldBeNullable || + options.nullableModels.contains(className) || refSchema?.shouldBeNullable == true || !requiredProperties.contains(propertyKey); @@ -804,7 +806,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - if ((prop.shouldBeNullable || options.nullableModels.contains(className)) && + if (prop.shouldBeNullable || + options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } From 0bc3f5884c36ad229c73f9e572cdb33ec8cd70a1 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Dec 2023 15:21:50 +0300 Subject: [PATCH 71/93] Added ability to rename downloaded files --- CHANGELOG.md | 8 ++++++++ lib/src/models/generator_options.dart | 21 ++++++++++++++++++++- lib/src/models/generator_options.g2.dart | 16 +++++++++++++++- lib/swagger_dart_code_generator.dart | 17 ++++++++++------- pubspec.yaml | 2 +- 5 files changed, 54 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9505abd..15a72b9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +# 2.13.5 + +* ***Breaking*** Added ability to rename downloaded swagger files ([#558](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/558)) + +# 2.14.1 + +* Added `ErrorConverter` to create method + # 2.13.4 * Make `readOnly` and `writeOnly` fields as `nullable` and `not required` ([#487](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/487)) diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 2ad1a364..997dcee4 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -81,7 +81,7 @@ class GeneratorOptions { final List additionalHeaders; @JsonKey(defaultValue: []) - List inputUrls; + List inputUrls; @JsonKey(defaultValue: []) List nullableModels; @@ -200,6 +200,25 @@ class DefaultHeaderValueMap { _$DefaultHeaderValueMapFromJson(json); } +@JsonSerializable(fieldRename: FieldRename.snake) +class InputUrl { + InputUrl({ + required this.url, + this.fileName, + }); + + @JsonKey() + final String url; + + @JsonKey() + final String? fileName; + + Map toJson() => _$InputUrlToJson(this); + + factory InputUrl.fromJson(Map json) => + _$InputUrlFromJson(json); +} + @JsonSerializable(fieldRename: FieldRename.snake) class OverridenModelsItem { @JsonKey() diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 477b1347..4a532b2b 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -59,7 +59,8 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( .toList() ?? [], inputUrls: (json['input_urls'] as List?) - ?.map((e) => e as String) + ?.map( + (e) => InputUrl.fromJson(Map.from(e as Map))) .toList() ?? [], nullableModels: (json['nullable_models'] as List?) @@ -85,6 +86,8 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( .toList() ?? [], multipartFileType: json['multipart_file_type'] as String? ?? 'List', + urlencodedFileType: + json['urlencoded_file_type'] as String? ?? 'Map', ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => @@ -96,6 +99,7 @@ Map _$GeneratorOptionsToJson(GeneratorOptions instance) => 'override_to_string': instance.overrideToString, 'override_equals_and_hashcode': instance.overrideEqualsAndHashcode, 'multipart_file_type': instance.multipartFileType, + 'urlencoded_file_type': instance.urlencodedFileType, 'with_converter': instance.withConverter, 'overriden_models': instance.overridenModels, 'generate_to_json_for': instance.generateToJsonFor, @@ -165,6 +169,16 @@ Map _$DefaultHeaderValueMapToJson( 'default_value': instance.defaultValue, }; +InputUrl _$InputUrlFromJson(Map json) => InputUrl( + url: json['url'] as String, + fileName: json['file_name'] as String?, + ); + +Map _$InputUrlToJson(InputUrl instance) => { + 'url': instance.url, + 'file_name': instance.fileName, + }; + OverridenModelsItem _$OverridenModelsItemFromJson(Map json) => OverridenModelsItem( fileName: json['file_name'] as String, diff --git a/lib/swagger_dart_code_generator.dart b/lib/swagger_dart_code_generator.dart index dba7e1ad..55ab9183 100644 --- a/lib/swagger_dart_code_generator.dart +++ b/lib/swagger_dart_code_generator.dart @@ -46,8 +46,9 @@ String _getAdditionalResultPath(GeneratorOptions options) { } if (options.inputUrls.isNotEmpty) { + final firstUrl = options.inputUrls.first; final path = normalize( - '${options.inputFolder}${getFileNameBase(options.inputUrls.first)}'); + '${options.inputFolder}${firstUrl.fileName ?? getFileNameBase(firstUrl.url)}'); File(path).createSync(); return path; } @@ -71,7 +72,7 @@ Map> _generateExtensions(GeneratorOptions options) { final fileNames = filesList.map((e) => getFileNameBase(e.path)); allFiledList.addAll(filesPaths); - allFiledList.addAll(options.inputUrls); + allFiledList.addAll(options.inputUrls.map((e) => e.fileName ?? e.url)); result[additionalResultPath] = {}; @@ -88,12 +89,14 @@ Map> _generateExtensions(GeneratorOptions options) { result[url]!.add(join(out, '$name$_outputResponsesFileExtension')); } - for (var url in options.inputUrls) { - if (fileNames.contains(getFileNameBase(url))) { + for (var inputUrl in options.inputUrls) { + if (fileNames + .contains(getFileNameBase(inputUrl.fileName ?? inputUrl.url))) { continue; } - final name = removeFileExtension(getFileNameBase(url)); + final name = + removeFileExtension(getFileNameBase(inputUrl.fileName ?? inputUrl.url)); result[additionalResultPath]!.add(join(out, '$name$_outputFileExtension')); result[additionalResultPath]! @@ -139,9 +142,9 @@ class SwaggerDartCodeGenerator implements Builder { Future build(BuildStep buildStep) async { if (buildStep.inputId.path == additionalResultPath) { for (final url in options.inputUrls) { - final fileNameWithExtension = getFileNameBase(url); + final fileNameWithExtension = getFileNameBase(url.fileName ?? url.url); - final contents = await _download(url); + final contents = await _download(url.url); final filePath = join(options.inputFolder, fileNameWithExtension); await File(filePath).create(); diff --git a/pubspec.yaml b/pubspec.yaml index ec174a72..3063e3ac 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.13.4 +version: 2.13.5 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 669d5b2c5ec71b1242f3163a97f5f5b7d5fea331 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 22 Dec 2023 15:22:17 +0300 Subject: [PATCH 72/93] Updated example --- example/build.yaml | 5 +- ..._service_json.json => some_file_name.json} | 0 .../swagger_generated_code/client_index.dart | 4 +- ...dart => some_file_name.enums.swagger.dart} | 0 ...rt => some_file_name.swagger.chopper.dart} | 8 +- .../some_file_name.swagger.dart | 1253 +++++++++++++++++ ...r.g.dart => some_file_name.swagger.g.dart} | 64 +- 7 files changed, 1325 insertions(+), 9 deletions(-) rename example/input_folder/{pet_service_json.json => some_file_name.json} (100%) rename example/lib/swagger_generated_code/{pet_service_json.enums.swagger.dart => some_file_name.enums.swagger.dart} (100%) rename example/lib/swagger_generated_code/{pet_service_json.swagger.chopper.dart => some_file_name.swagger.chopper.dart} (98%) create mode 100644 example/lib/swagger_generated_code/some_file_name.swagger.dart rename example/lib/swagger_generated_code/{pet_service_json.swagger.g.dart => some_file_name.swagger.g.dart} (56%) diff --git a/example/build.yaml b/example/build.yaml index 416a295f..d2858c56 100644 --- a/example/build.yaml +++ b/example/build.yaml @@ -16,8 +16,9 @@ targets: input_folder: "input_folder/" output_folder: "lib/swagger_generated_code/" input_urls: - - "https://raw.githubusercontent.com/epam-cross-platform-lab/swagger-dart-code-generator/master/example/input_folder/pet_service_json.json" - - "https://raw.githubusercontent.com/epam-cross-platform-lab/swagger-dart-code-generator/master/example/input_folder/pet_service_yaml.yaml" + - url: "https://raw.githubusercontent.com/epam-cross-platform-lab/swagger-dart-code-generator/master/example/input_folder/pet_service_json.json" + file_name: "some_file_name.json" + - url: "https://raw.githubusercontent.com/epam-cross-platform-lab/swagger-dart-code-generator/master/example/input_folder/pet_service_yaml.yaml" with_base_url: true with_converter: true use_path_for_request_names: true diff --git a/example/input_folder/pet_service_json.json b/example/input_folder/some_file_name.json similarity index 100% rename from example/input_folder/pet_service_json.json rename to example/input_folder/some_file_name.json diff --git a/example/lib/swagger_generated_code/client_index.dart b/example/lib/swagger_generated_code/client_index.dart index 00b3fd27..d1eb6b26 100644 --- a/example/lib/swagger_generated_code/client_index.dart +++ b/example/lib/swagger_generated_code/client_index.dart @@ -1,5 +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; +export 'some_file_name.swagger.dart' show SomeFileName; +export 'some_file_name.swagger.dart' show SomeFileName; diff --git a/example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart b/example/lib/swagger_generated_code/some_file_name.enums.swagger.dart similarity index 100% rename from example/lib/swagger_generated_code/pet_service_json.enums.swagger.dart rename to example/lib/swagger_generated_code/some_file_name.enums.swagger.dart diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart b/example/lib/swagger_generated_code/some_file_name.swagger.chopper.dart similarity index 98% rename from example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart rename to example/lib/swagger_generated_code/some_file_name.swagger.chopper.dart index 04a3500d..c565f749 100644 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.chopper.dart +++ b/example/lib/swagger_generated_code/some_file_name.swagger.chopper.dart @@ -1,20 +1,20 @@ //Generated code -part of 'pet_service_json.swagger.dart'; +part of 'some_file_name.swagger.dart'; // ************************************************************************** // ChopperGenerator // ************************************************************************** // ignore_for_file: always_put_control_body_on_new_line, always_specify_types, prefer_const_declarations, unnecessary_brace_in_string_interps -class _$PetServiceJson extends PetServiceJson { - _$PetServiceJson([ChopperClient? client]) { +class _$SomeFileName extends SomeFileName { + _$SomeFileName([ChopperClient? client]) { if (client == null) return; this.client = client; } @override - final definitionType = PetServiceJson; + final definitionType = SomeFileName; @override Future> _petPost({ diff --git a/example/lib/swagger_generated_code/some_file_name.swagger.dart b/example/lib/swagger_generated_code/some_file_name.swagger.dart new file mode 100644 index 00000000..e222bfc9 --- /dev/null +++ b/example/lib/swagger_generated_code/some_file_name.swagger.dart @@ -0,0 +1,1253 @@ +// ignore_for_file: type=lint + +import 'package:json_annotation/json_annotation.dart'; +import 'package:collection/collection.dart'; +import 'dart:convert'; + +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 'some_file_name.enums.swagger.dart' as enums; +export 'some_file_name.enums.swagger.dart'; + +part 'some_file_name.swagger.chopper.dart'; +part 'some_file_name.swagger.g.dart'; + +// ************************************************************************** +// SwaggerChopperGenerator +// ************************************************************************** + +@ChopperApi() +abstract class SomeFileName extends ChopperService { + static SomeFileName create({ + ChopperClient? client, + http.Client? httpClient, + Authenticator? authenticator, + ErrorConverter? errorConverter, + Converter? converter, + Uri? baseUrl, + Iterable? interceptors, + }) { + if (client != null) { + return _$SomeFileName(client); + } + + final newClient = ChopperClient( + services: [_$SomeFileName()], + converter: converter ?? $JsonSerializableConverter(), + interceptors: interceptors ?? [], + client: httpClient, + authenticator: authenticator, + errorConverter: errorConverter, + baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); + return _$SomeFileName(newClient); + } + + ///Add a new pet to the store + ///@param body Pet object that needs to be added to the store + Future petPost({ + required Pet? body, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); + + return _petPost(body: body, cacheControl: cacheControl?.toString()); + } + + ///Add a new pet to the store + ///@param body Pet object that needs to be added to the store + @Post(path: '/pet') + Future _petPost({ + @Body() required Pet? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Update an existing pet + ///@param body Pet object that needs to be added to the store + Future petPut({ + required Pet? body, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); + + return _petPut(body: body, cacheControl: cacheControl?.toString()); + } + + ///Update an existing pet + ///@param body Pet object that needs to be added to the store + @Put(path: '/pet') + Future _petPut({ + @Body() required Pet? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Finds Pets by status + ///@param status Status values that need to be considered for filter + Future>> petFindByStatusGet({ + required List? status, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); + + return _petFindByStatusGet( + 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 List? status, + @Header('Cache-Control') String? cacheControl, + }); + + ///Finds Pets by tags + ///@param tags Tags to filter by + Future>> petFindByTagsGet({ + required List? tags, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); + + 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, + @Header('Cache-Control') String? cacheControl, + }); + + ///Find pet by ID + ///@param petId ID of pet to return + Future> petPetIdGet({ + required int? petId, + dynamic apiKey, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); + + return _petPetIdGet( + petId: petId, + apiKey: apiKey?.toString(), + cacheControl: cacheControl?.toString()); + } + + ///Find pet by ID + ///@param petId ID of pet to return + @Get(path: '/pet/{petId}') + Future> _petPetIdGet({ + @Path('petId') required int? petId, + @Header('api_key') String? apiKey, + @Header('Cache-Control') String? cacheControl, + }); + + ///Updates a pet in the store with form data + ///@param petId ID of pet that needs to be updated + ///@param name Updated name of the pet + ///@param status Updated status of the pet + Future petPetIdPost({ + required int? petId, + String? name, + String? status, + dynamic cacheControl, + }) { + return _petPetIdPost( + petId: petId, + name: name, + status: status, + cacheControl: cacheControl?.toString()); + } + + ///Updates a pet in the store with form data + ///@param petId ID of pet that needs to be updated + ///@param name Updated name of the pet + ///@param status Updated status of the pet + @Post( + path: '/pet/{petId}', + optionalBody: true, + ) + Future _petPetIdPost({ + @Path('petId') required int? petId, + @Field('name') String? name, + @Field('status') String? status, + @Header('Cache-Control') String? cacheControl, + }); + + ///Deletes a pet + ///@param api_key + ///@param petId Pet id to delete + Future petPetIdDelete({ + String? apiKey, + required int? petId, + dynamic cacheControl, + }) { + return _petPetIdDelete( + apiKey: apiKey?.toString(), + petId: petId, + cacheControl: cacheControl?.toString()); + } + + ///Deletes a pet + ///@param api_key + ///@param petId Pet id to delete + @Delete(path: '/pet/{petId}') + Future _petPetIdDelete({ + @Header('api_key') String? apiKey, + @Path('petId') required int? petId, + @Header('Cache-Control') String? cacheControl, + }); + + ///uploads an image + ///@param petId ID of pet to update + ///@param additionalMetadata Additional data to pass to server + ///@param file file to upload + Future> petPetIdUploadImagePost({ + required int? petId, + String? additionalMetadata, + List? file, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent( + ApiResponse, () => ApiResponse.fromJsonFactory); + + return _petPetIdUploadImagePost( + petId: petId, + additionalMetadata: additionalMetadata, + file: file, + cacheControl: cacheControl?.toString()); + } + + ///uploads an image + ///@param petId ID of pet to update + ///@param additionalMetadata Additional data to pass to server + ///@param file file to upload + @Post( + path: '/pet/{petId}/uploadImage', + optionalBody: true, + ) + Future> _petPetIdUploadImagePost({ + @Path('petId') required int? petId, + @Field('additionalMetadata') String? additionalMetadata, + @Field('file') List? file, + @Header('Cache-Control') String? cacheControl, + }); + + ///Returns pet inventories by status + Future> storeInventoryGet({ + dynamic apiKey, + dynamic cacheControl, + }) { + return _storeInventoryGet( + apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); + } + + ///Returns pet inventories by status + @Get(path: '/store/inventory') + Future> _storeInventoryGet({ + @Header('api_key') String? apiKey, + @Header('Cache-Control') String? cacheControl, + }); + + ///Place an order for a pet + ///@param body order placed for purchasing the pet + Future> storeOrderPost({ + required Order? body, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); + + return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); + } + + ///Place an order for a pet + ///@param body order placed for purchasing the pet + @Post(path: '/store/order') + Future> _storeOrderPost({ + @Body() required Order? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Find purchase order by ID + ///@param orderId ID of pet that needs to be fetched + Future> storeOrderOrderIdGet({ + required int? orderId, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); + + return _storeOrderOrderIdGet( + orderId: orderId, cacheControl: cacheControl?.toString()); + } + + ///Find purchase order by ID + ///@param orderId ID of pet that needs to be fetched + @Get(path: '/store/order/{orderId}') + Future> _storeOrderOrderIdGet({ + @Path('orderId') required int? orderId, + @Header('Cache-Control') String? cacheControl, + }); + + ///Delete purchase order by ID + ///@param orderId ID of the order that needs to be deleted + Future storeOrderOrderIdDelete({ + required int? orderId, + dynamic cacheControl, + }) { + return _storeOrderOrderIdDelete( + orderId: orderId, cacheControl: cacheControl?.toString()); + } + + ///Delete purchase order by ID + ///@param orderId ID of the order that needs to be deleted + @Delete(path: '/store/order/{orderId}') + Future _storeOrderOrderIdDelete({ + @Path('orderId') required int? orderId, + @Header('Cache-Control') String? cacheControl, + }); + + ///Create user + ///@param body Created user object + Future userPost({ + required User? body, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); + + return _userPost(body: body, cacheControl: cacheControl?.toString()); + } + + ///Create user + ///@param body Created user object + @Post(path: '/user') + Future _userPost({ + @Body() required User? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Creates list of users with given input array + ///@param body List of user object + Future userCreateWithArrayPost({ + required List? body, + dynamic cacheControl, + }) { + return _userCreateWithArrayPost( + body: body, cacheControl: cacheControl?.toString()); + } + + ///Creates list of users with given input array + ///@param body List of user object + @Post(path: '/user/createWithArray') + Future _userCreateWithArrayPost({ + @Body() required List? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Creates list of users with given input array + ///@param body List of user object + Future userCreateWithListPost({ + required List? body, + dynamic cacheControl, + }) { + return _userCreateWithListPost( + body: body, cacheControl: cacheControl?.toString()); + } + + ///Creates list of users with given input array + ///@param body List of user object + @Post(path: '/user/createWithList') + Future _userCreateWithListPost({ + @Body() required List? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Logs user into the system + ///@param username The user name for login + ///@param password The password for login in clear text + Future> userLoginGet({ + required String? username, + required String? password, + dynamic cacheControl, + }) { + return _userLoginGet( + username: username, + password: password, + cacheControl: cacheControl?.toString()); + } + + ///Logs user into the system + ///@param username The user name for login + ///@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, + @Header('Cache-Control') String? cacheControl, + }); + + ///Logs out current logged in user session + Future userLogoutGet({dynamic cacheControl}) { + return _userLogoutGet(cacheControl: cacheControl?.toString()); + } + + ///Logs out current logged in user session + @Get(path: '/user/logout') + Future _userLogoutGet( + {@Header('Cache-Control') String? cacheControl}); + + ///Get user by user name + ///@param username The name that needs to be fetched. Use user1 for testing. + Future> userUsernameGet({ + required String? username, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); + + return _userUsernameGet( + username: username, cacheControl: cacheControl?.toString()); + } + + ///Get user by user name + ///@param username The name that needs to be fetched. Use user1 for testing. + @Get(path: '/user/{username}') + Future> _userUsernameGet({ + @Path('username') required String? username, + @Header('Cache-Control') String? cacheControl, + }); + + ///Updated user + ///@param username name that need to be updated + ///@param body Updated user object + Future userUsernamePut({ + required String? username, + required User? body, + dynamic cacheControl, + }) { + generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); + + return _userUsernamePut( + username: username, body: body, cacheControl: cacheControl?.toString()); + } + + ///Updated user + ///@param username name that need to be updated + ///@param body Updated user object + @Put(path: '/user/{username}') + Future _userUsernamePut({ + @Path('username') required String? username, + @Body() required User? body, + @Header('Cache-Control') String? cacheControl, + }); + + ///Delete user + ///@param username The name that needs to be deleted + Future userUsernameDelete({ + required String? username, + dynamic cacheControl, + }) { + return _userUsernameDelete( + username: username, cacheControl: cacheControl?.toString()); + } + + ///Delete user + ///@param username The name that needs to be deleted + @Delete(path: '/user/{username}') + Future _userUsernameDelete({ + @Path('username') required String? username, + @Header('Cache-Control') String? cacheControl, + }); +} + +@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 { + const Category({ + this.id, + this.name, + }); + + factory Category.fromJson(Map json) => + _$CategoryFromJson(json); + + static const toJsonFactory = _$CategoryToJson; + Map toJson() => _$CategoryToJson(this); + + @JsonKey(name: 'id', includeIfNull: false) + final int? id; + @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') + final String? name; + static const fromJsonFactory = _$CategoryFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is Category && + (identical(other.id, id) || + const DeepCollectionEquality().equals(other.id, id)) && + (identical(other.name, name) || + const DeepCollectionEquality().equals(other.name, name))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(id) ^ + const DeepCollectionEquality().hash(name) ^ + runtimeType.hashCode; +} + +extension $CategoryExtension on Category { + Category copyWith({int? id, String? name}) { + return Category(id: id ?? this.id, name: name ?? this.name); + } + + Category copyWithWrapped({Wrapped? id, Wrapped? name}) { + return Category( + id: (id != null ? id.value : this.id), + name: (name != null ? name.value : this.name)); + } +} + +@JsonSerializable(explicitToJson: true) +class User { + const User({ + this.id, + this.username, + this.firstName, + this.lastName, + this.email, + this.password, + this.phone, + this.userStatus, + }); + + factory User.fromJson(Map json) => _$UserFromJson(json); + + static const toJsonFactory = _$UserToJson; + Map toJson() => _$UserToJson(this); + + @JsonKey(name: 'id', includeIfNull: false) + final int? id; + @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') + final String? username; + @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') + final String? firstName; + @JsonKey(name: 'lastName', includeIfNull: false, defaultValue: '') + final String? lastName; + @JsonKey(name: 'email', includeIfNull: false, defaultValue: '') + final String? email; + @JsonKey(name: 'password', includeIfNull: false, defaultValue: '') + final String? password; + @JsonKey(name: 'phone', includeIfNull: false, defaultValue: '') + final String? phone; + @JsonKey(name: 'userStatus', includeIfNull: false) + final int? userStatus; + static const fromJsonFactory = _$UserFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is User && + (identical(other.id, id) || + const DeepCollectionEquality().equals(other.id, id)) && + (identical(other.username, username) || + const DeepCollectionEquality() + .equals(other.username, username)) && + (identical(other.firstName, firstName) || + const DeepCollectionEquality() + .equals(other.firstName, firstName)) && + (identical(other.lastName, lastName) || + const DeepCollectionEquality() + .equals(other.lastName, lastName)) && + (identical(other.email, email) || + const DeepCollectionEquality().equals(other.email, email)) && + (identical(other.password, password) || + const DeepCollectionEquality() + .equals(other.password, password)) && + (identical(other.phone, phone) || + const DeepCollectionEquality().equals(other.phone, phone)) && + (identical(other.userStatus, userStatus) || + const DeepCollectionEquality() + .equals(other.userStatus, userStatus))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(id) ^ + const DeepCollectionEquality().hash(username) ^ + const DeepCollectionEquality().hash(firstName) ^ + const DeepCollectionEquality().hash(lastName) ^ + const DeepCollectionEquality().hash(email) ^ + const DeepCollectionEquality().hash(password) ^ + const DeepCollectionEquality().hash(phone) ^ + const DeepCollectionEquality().hash(userStatus) ^ + runtimeType.hashCode; +} + +extension $UserExtension on User { + User copyWith( + {int? id, + String? username, + String? firstName, + String? lastName, + String? email, + String? password, + String? phone, + int? userStatus}) { + return User( + id: id ?? this.id, + username: username ?? this.username, + firstName: firstName ?? this.firstName, + lastName: lastName ?? this.lastName, + email: email ?? this.email, + password: password ?? this.password, + phone: phone ?? this.phone, + userStatus: userStatus ?? this.userStatus); + } + + User copyWithWrapped( + {Wrapped? id, + Wrapped? username, + Wrapped? firstName, + Wrapped? lastName, + Wrapped? email, + Wrapped? password, + Wrapped? phone, + Wrapped? userStatus}) { + return User( + id: (id != null ? id.value : this.id), + username: (username != null ? username.value : this.username), + firstName: (firstName != null ? firstName.value : this.firstName), + lastName: (lastName != null ? lastName.value : this.lastName), + email: (email != null ? email.value : this.email), + password: (password != null ? password.value : this.password), + phone: (phone != null ? phone.value : this.phone), + userStatus: (userStatus != null ? userStatus.value : this.userStatus)); + } +} + +@JsonSerializable(explicitToJson: true) +class 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 int? id; + @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') + final String? name; + static const fromJsonFactory = _$TagFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is Tag && + (identical(other.id, id) || + const DeepCollectionEquality().equals(other.id, id)) && + (identical(other.name, name) || + const DeepCollectionEquality().equals(other.name, name))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(id) ^ + const DeepCollectionEquality().hash(name) ^ + runtimeType.hashCode; +} + +extension $TagExtension on Tag { + Tag copyWith({int? id, String? name}) { + return Tag(id: id ?? this.id, name: name ?? this.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 { + const Pet({ + this.id, + this.category, + 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 int? 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: petStatusNullableToJson, + fromJson: petStatusNullableFromJson, + ) + final enums.PetStatus? status; + static const fromJsonFactory = _$PetFromJson; + + @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( + {int? 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 { + const ApiResponse({ + this.code, + this.type, + this.message, + }); + + 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: '') + final String? type; + @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') + final String? message; + static const fromJsonFactory = _$ApiResponseFromJson; + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other is ApiResponse && + (identical(other.code, code) || + const DeepCollectionEquality().equals(other.code, code)) && + (identical(other.type, type) || + const DeepCollectionEquality().equals(other.type, type)) && + (identical(other.message, message) || + const DeepCollectionEquality().equals(other.message, message))); + } + + @override + String toString() => jsonEncode(this); + + @override + int get hashCode => + const DeepCollectionEquality().hash(code) ^ + const DeepCollectionEquality().hash(type) ^ + const DeepCollectionEquality().hash(message) ^ + runtimeType.hashCode; +} + +extension $ApiResponseExtension on ApiResponse { + ApiResponse copyWith({int? code, String? type, String? message}) { + return ApiResponse( + code: code ?? this.code, + type: type ?? this.type, + message: message ?? this.message); + } + + ApiResponse copyWithWrapped( + {Wrapped? code, + Wrapped? type, + Wrapped? message}) { + return ApiResponse( + code: (code != null ? code.value : this.code), + type: (type != null ? type.value : this.type), + message: (message != null ? message.value : this.message)); + } +} + +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.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 []; + } + + return orderStatus.map((e) => e.value!).toList(); +} + +List orderStatusListFromJson( + List? orderStatus, [ + List? defaultValue, +]) { + if (orderStatus == null) { + return defaultValue ?? []; + } + + return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); +} + +List? orderStatusNullableListFromJson( + List? orderStatus, [ + List? defaultValue, +]) { + if (orderStatus == null) { + return defaultValue; + } + + return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); +} + +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.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 []; + } + + return petStatus.map((e) => e.value!).toList(); +} + +List petStatusListFromJson( + List? petStatus, [ + List? defaultValue, +]) { + if (petStatus == null) { + return defaultValue ?? []; + } + + return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); +} + +List? petStatusNullableListFromJson( + List? petStatus, [ + List? defaultValue, +]) { + if (petStatus == null) { + return defaultValue; + } + + return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); +} + +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.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) { + return []; + } + + return petFindByStatusGetStatus.map((e) => e.value!).toList(); +} + +List petFindByStatusGetStatusListFromJson( + List? petFindByStatusGetStatus, [ + List? defaultValue, +]) { + if (petFindByStatusGetStatus == null) { + return defaultValue ?? []; + } + + return petFindByStatusGetStatus + .map((e) => petFindByStatusGetStatusFromJson(e.toString())) + .toList(); +} + +List? + petFindByStatusGetStatusNullableListFromJson( + List? petFindByStatusGetStatus, [ + List? defaultValue, +]) { + if (petFindByStatusGetStatus == null) { + return defaultValue; + } + + return petFindByStatusGetStatus + .map((e) => petFindByStatusGetStatusFromJson(e.toString())) + .toList(); +} + +typedef $JsonFactory = T Function(Map json); + +class $CustomJsonDecoder { + $CustomJsonDecoder(this.factories); + + final Map factories; + + dynamic decode(dynamic entity) { + if (entity is Iterable) { + return _decodeList(entity); + } + + if (entity is T) { + return entity; + } + + if (isTypeOf()) { + return entity; + } + + if (isTypeOf()) { + return entity; + } + + if (entity is Map) { + return _decodeMap(entity); + } + + return entity; + } + + T _decodeMap(Map values) { + final jsonFactory = factories[T]; + if (jsonFactory == null || jsonFactory is! $JsonFactory) { + return throw "Could not find factory for type $T. Is '$T: $T.fromJsonFactory' included in the CustomJsonDecoder instance creation in bootstrapper.dart?"; + } + + return jsonFactory(values); + } + + List _decodeList(Iterable values) => + values.where((v) => v != null).map((v) => decode(v) as T).toList(); +} + +class $JsonSerializableConverter extends chopper.JsonConverter { + @override + FutureOr> convertResponse( + chopper.Response response) async { + if (response.bodyString.isEmpty) { + // In rare cases, when let's say 204 (no content) is returned - + // we cannot decode the missing json with the result type specified + return chopper.Response(response.base, null, error: response.error); + } + + 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); + } +} + +final $jsonDecoder = $CustomJsonDecoder(generatedMapping); + +// ignore: unused_element +String? _dateToJson(DateTime? date) { + if (date == null) { + return null; + } + + final year = date.year.toString(); + final month = date.month < 10 ? '0${date.month}' : date.month.toString(); + final day = date.day < 10 ? '0${date.day}' : date.day.toString(); + + return '$year-$month-$day'; +} + +class Wrapped { + final T value; + const Wrapped.value(this.value); +} diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart b/example/lib/swagger_generated_code/some_file_name.swagger.g.dart similarity index 56% rename from example/lib/swagger_generated_code/pet_service_json.swagger.g.dart rename to example/lib/swagger_generated_code/some_file_name.swagger.g.dart index f1bb7df4..c40a379d 100644 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.g.dart +++ b/example/lib/swagger_generated_code/some_file_name.swagger.g.dart @@ -1,11 +1,40 @@ // GENERATED CODE - DO NOT MODIFY BY HAND -part of 'pet_service_json.swagger.dart'; +part of 'some_file_name.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 int?, name: json['name'] as String? ?? '', @@ -75,6 +104,39 @@ Map _$TagToJson(Tag instance) { return val; } +Pet _$PetFromJson(Map json) => Pet( + id: json['id'] as int?, + 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: petStatusNullableFromJson(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', petStatusNullableToJson(instance.status)); + return val; +} + ApiResponse _$ApiResponseFromJson(Map json) => ApiResponse( code: json['code'] as int?, type: json['type'] as String? ?? '', From 8b27c97dd55d8aa8113b172f303414e0237cc5aa Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Dec 2023 12:45:46 +0300 Subject: [PATCH 73/93] Implemented support of deprecated fields annotations --- lib/src/code_generators/constants.dart | 1 + .../swagger_models_generator.dart | 171 ++++++++++-------- .../requests/swagger_request.dart | 4 + .../requests/swagger_request.g2.dart | 2 + .../responses/swagger_schema.dart | 4 + .../responses/swagger_schema.g2.dart | 2 + 6 files changed, 110 insertions(+), 74 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 6852a51e..473eea5b 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -60,6 +60,7 @@ const kFormData = 'formData'; const kMultipart = 'multipart'; const kDateTimeFormat = 'date-time'; const kFactoryConverter = 'factoryConverter'; +const kDeprecatedAnnotation = '@deprecated'; const kDefaultBodyParameter = 'Object'; const kField = 'Field'; diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 6dce5ec8..25be4f2b 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -437,13 +437,14 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return ', includeIfNull: ${options.includeIfNull}'; } - String generatePropertyContentByDefault( - SwaggerSchema prop, - String propertyName, - List allEnumNames, - List allEnumListNames, - List requiredProperties, - ) { + String generatePropertyContentByDefault({ + required SwaggerSchema prop, + required String propertyName, + required List allEnumNames, + required List allEnumListNames, + required List requiredProperties, + required bool isDeprecated, + }) { var typeName = ''; if (prop.hasOriginalRef) { @@ -487,8 +488,9 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final jsonKeyContent = "@JsonKey(name: '$propertyKey'$includeIfNullString$dateToJsonValue${unknownEnumValue.jsonKey})\n"; + final deprecatedContent = isDeprecated ? '@deprecated\n' : ''; - return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; + return '\t$jsonKeyContent$deprecatedContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } JsonEnumValue generateEnumValue({ @@ -666,6 +668,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; + final deprecatedContent = + propertySchema.deprecated ? kDeprecatedAnnotation : ''; if (prop.shouldBeNullable || (options.nullableModels.contains(className) && @@ -673,7 +677,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName = typeName.makeNullable(); } - return '\t$jsonKeyContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; + return '\t$jsonKeyContent$deprecatedContent\tfinal $typeName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } String _validatePropertyKey(String key) { @@ -734,13 +738,15 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; + final deprecatedContent = prop.deprecated ? kDeprecatedAnnotation : ''; + if (prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } - return '\t$jsonKeyContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; + return '\t$jsonKeyContent$deprecatedContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; } String generatePropertyContentByRef( @@ -806,6 +812,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; + final deprecatedContent = + refSchema?.deprecated == true ? kDeprecatedAnnotation : ''; + if (prop.shouldBeNullable || options.nullableModels.contains(className) || !requiredProperties.contains(propertyKey)) { @@ -826,18 +835,19 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName += '?'; } - return '\t$jsonKeyContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; + return '\t$jsonKeyContent$deprecatedContent\tfinal $typeName $propertyName;${unknownEnumValue.fromJson}'; } - String generateEnumPropertyContent( - String key, - String className, - String propertyKey, - List allEnumNames, - List allEnumListNames, - SwaggerSchema prop, - List requiredProperties, - ) { + String generateEnumPropertyContent({ + required String key, + required String className, + required String propertyKey, + required List allEnumNames, + required List allEnumListNames, + required SwaggerSchema prop, + required List requiredProperties, + required bool isDeprecated, + }) { final enumName = getValidatedClassName(generateEnumName(className, key)); allEnumNames.add(enumName); @@ -863,6 +873,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr return ''' @JsonKey(${unknownEnumValue.jsonKey.substring(2)}$includeIfNullString) + ${isDeprecated ? kDeprecatedAnnotation : ''} final $enumPropertyName ${generateFieldName(key)}; ${unknownEnumValue.fromJson}'''; @@ -953,18 +964,19 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr return typeName; } - String generateListPropertyContent( - String propertyName, - String propertyKey, - String className, - SwaggerSchema prop, - List classesWithNullableLists, - List allEnumNames, - List allEnumListNames, - Map basicTypesMap, - List requiredProperties, - Map allClasses, - ) { + String generateListPropertyContent({ + required String propertyName, + required String propertyKey, + required String className, + required SwaggerSchema prop, + required List classesWithNullableLists, + required List allEnumNames, + required List allEnumListNames, + required Map basicTypesMap, + required List requiredProperties, + required Map allClasses, + required bool isDeprecated, + }) { final typeName = _generateListPropertyTypeName( allEnumListNames: allEnumListNames, allEnumNames: allEnumNames, @@ -1004,6 +1016,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr "@JsonKey(name: '$validatedPropertyKey'$includeIfNullString${unknownEnumValue.jsonKey})\n"; } + final deprecatedContent = isDeprecated ? kDeprecatedAnnotation : ''; + var listPropertyName = 'List<$typeName>'; if (prop.shouldBeNullable || @@ -1012,24 +1026,27 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr listPropertyName = listPropertyName.makeNullable(); } - return '$jsonKeyContent final $listPropertyName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; + return '$jsonKeyContent$deprecatedContent final $listPropertyName ${generateFieldName(propertyName)};${unknownEnumValue.fromJson}'; } - String generateGeneralPropertyContent( - String propertyName, - String propertyKey, - String className, - List defaultValues, - SwaggerSchema prop, - List allEnumNames, - List allEnumListNames, - List requiredProperties, - ) { + String generateGeneralPropertyContent({ + required String propertyName, + required String propertyKey, + required String className, + required List defaultValues, + required SwaggerSchema prop, + required List allEnumNames, + required List allEnumListNames, + required List requiredProperties, + required bool isDeprecated, + }) { final includeIfNullString = generateIncludeIfNullString(); var jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString"; + final isDeprecatedContent = isDeprecated ? kDeprecatedAnnotation : ''; + var typeName = ''; if (prop.hasAdditionalProperties && prop.type == 'object') { @@ -1085,7 +1102,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr typeName = typeName.makeNullable(); } - return '\t$jsonKeyContent final $typeName $propertyName;${unknownEnumValue.fromJson}'; + return '\t$jsonKeyContent$isDeprecatedContent final $typeName $propertyName;${unknownEnumValue.fromJson}'; } String generatePropertyContentByType( @@ -1100,41 +1117,45 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr Map basicTypesMap, List requiredProperties, Map allClasses, + bool isDeprecated, ) { switch (prop.type) { case 'array': return generateListPropertyContent( - propertyName, - propertyKey, - className, - prop, - classesWithNullableLists, - allEnumsNames, - allEnumListNames, - basicTypesMap, - requiredProperties, - allClasses, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + prop: prop, + classesWithNullableLists: classesWithNullableLists, + allEnumNames: allEnumsNames, + allEnumListNames: allEnumListNames, + basicTypesMap: basicTypesMap, + requiredProperties: requiredProperties, + allClasses: allClasses, + isDeprecated: isDeprecated, ); case 'enum': return generateEnumPropertyContent( - propertyName, - className, - propertyKey, - allEnumsNames, - allEnumListNames, - prop, - requiredProperties, + key: propertyName, + className: className, + propertyKey: propertyKey, + allEnumNames: allEnumsNames, + allEnumListNames: allEnumListNames, + prop: prop, + requiredProperties: requiredProperties, + isDeprecated: isDeprecated, ); default: return generateGeneralPropertyContent( - propertyName, - propertyKey, - className, - defaultValues, - prop, - allEnumsNames, - allEnumListNames, - requiredProperties, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + defaultValues: defaultValues, + prop: prop, + allEnumNames: allEnumsNames, + allEnumListNames: allEnumListNames, + requiredProperties: requiredProperties, + isDeprecated: isDeprecated, ); } } @@ -1198,6 +1219,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr basicTypesMap, requiredProperties, allClasses, + prop.deprecated, )); } else if (prop.allOf.isNotEmpty) { results.add( @@ -1237,11 +1259,12 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr )); } else { results.add(generatePropertyContentByDefault( - prop, - propertyName, - allEnumNames, - allEnumListNames, - requiredProperties, + prop: prop, + propertyName: propertyName, + allEnumNames: allEnumNames, + allEnumListNames: allEnumListNames, + requiredProperties: requiredProperties, + isDeprecated: prop.deprecated, )); } } diff --git a/lib/src/swagger_models/requests/swagger_request.dart b/lib/src/swagger_models/requests/swagger_request.dart index df8a66a4..259c7967 100644 --- a/lib/src/swagger_models/requests/swagger_request.dart +++ b/lib/src/swagger_models/requests/swagger_request.dart @@ -18,6 +18,7 @@ class SwaggerRequest { this.produces = const [], this.security = const [], this.requestBody, + this.deprecated = false, }); @JsonKey(name: 'summary', defaultValue: '') @@ -26,6 +27,9 @@ class SwaggerRequest { @JsonKey(name: 'description', defaultValue: '') String description; + @JsonKey(name: 'deprecated', defaultValue: false) + bool deprecated; + @JsonKey(name: 'operationId', defaultValue: '') String operationId; diff --git a/lib/src/swagger_models/requests/swagger_request.g2.dart b/lib/src/swagger_models/requests/swagger_request.g2.dart index 22955754..83fff390 100644 --- a/lib/src/swagger_models/requests/swagger_request.g2.dart +++ b/lib/src/swagger_models/requests/swagger_request.g2.dart @@ -11,6 +11,7 @@ SwaggerRequest _$SwaggerRequestFromJson(Map json) => summary: json['summary'] as String? ?? '', description: json['description'] as String? ?? '', operationId: json['operationId'] as String? ?? '', + deprecated: json['deprecated'] as bool? ?? false, consumes: (json['consumes'] as List?) ?.map((e) => e as String) .toList() ?? @@ -42,6 +43,7 @@ Map _$SwaggerRequestToJson(SwaggerRequest instance) => 'summary': instance.summary, 'description': instance.description, 'operationId': instance.operationId, + 'deprecated': instance.deprecated, 'consumes': instance.consumes, 'produces': instance.produces, 'responses': instance.responses, diff --git a/lib/src/swagger_models/responses/swagger_schema.dart b/lib/src/swagger_models/responses/swagger_schema.dart index 5f91fb72..09ecb64c 100644 --- a/lib/src/swagger_models/responses/swagger_schema.dart +++ b/lib/src/swagger_models/responses/swagger_schema.dart @@ -27,6 +27,7 @@ class SwaggerSchema { this.title = '', this.readOnly = false, this.writeOnly = false, + this.deprecated = false, }); @JsonKey(name: 'readOnly', defaultValue: false) @@ -38,6 +39,9 @@ class SwaggerSchema { @JsonKey(name: 'type', defaultValue: '') String type; + @JsonKey(name: 'deprecated', defaultValue: false) + bool deprecated; + @JsonKey(name: 'title', defaultValue: '') String title; diff --git a/lib/src/swagger_models/responses/swagger_schema.g2.dart b/lib/src/swagger_models/responses/swagger_schema.g2.dart index deb0075f..2d9c735b 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g2.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g2.dart @@ -44,6 +44,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => title: json['title'] as String? ?? '', readOnly: json['readOnly'] as bool? ?? false, writeOnly: json['writeOnly'] as bool? ?? false, + deprecated: json['deprecated'] as bool? ?? false, enumNames: (json['enumNames'] as List?) ?.map((e) => e as String) .toList(), @@ -77,6 +78,7 @@ Map _$SwaggerSchemaToJson(SwaggerSchema instance) => 'title': instance.title, 'readOnly': instance.readOnly, 'writeOnly': instance.writeOnly, + 'deprecated': instance.deprecated, 'additionalProperties': instance.hasAdditionalProperties, 'enumNames': instance.enumNames, }; From 4e2b462a690c582293ca29a7ca89c5d8bcc87f22 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Dec 2023 12:57:15 +0300 Subject: [PATCH 74/93] Added support of deprecated requests annotations --- .../swagger_requests_generator.dart | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index a9637d5d..09a141d7 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -216,8 +216,14 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { componentsParameters: swaggerRoot.components?.parameters ?? {}, )) ..name = methodName - ..annotations.addAll(_getMethodAnnotation(requestType, annotationPath, - hasOptionalBody, isMultipart, isUrlencoded)) + ..annotations.addAll(_getMethodAnnotation( + requestType: requestType, + path: annotationPath, + hasOptionalBody: hasOptionalBody, + isMultipart: isMultipart, + isUrlencoded: isUrlencoded, + isDeprecated: swaggerRequest.deprecated, + )) ..returns = Reference(returns)); final allModels = _getAllMethodModels( @@ -227,7 +233,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ); final privateMethod = _getPrivateMethod(method); - final publicMethod = _getPublicMethod(method, allModels); + final publicMethod = _getPublicMethod( + method, + allModels, + swaggerRequest.deprecated, + ); methods.addAll([publicMethod, privateMethod]); }); }); @@ -412,7 +422,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ); } - Method _getPublicMethod(Method method, List allModels) { + Method _getPublicMethod( + Method method, List allModels, bool isDeprecated) { final parameters = method.optionalParameters.map((p) => p.copyWith(annotations: [])); @@ -422,6 +433,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..docs.addAll(method.docs) ..name = method.name ..returns = method.returns + ..annotations.addAll([if (isDeprecated) refer('deprecated')]) ..body = _generatePublicMethodCode( method.optionalParameters, method.name!, @@ -472,9 +484,16 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { '$allModelsString\nreturn _$publicMethodName($parametersListString);'); } - List _getMethodAnnotation(String requestType, String path, - bool hasOptionalBody, bool isMultipart, bool isUrlencoded) { + List _getMethodAnnotation({ + required String requestType, + required String path, + required bool hasOptionalBody, + required bool isMultipart, + required bool isUrlencoded, + required bool isDeprecated, + }) { return [ + if (isDeprecated) refer('deprecated'), refer(requestType.pascalCase).call( [], { From 28b606b38958c1272fc47160f0452c914662e4ef Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Dec 2023 13:10:20 +0300 Subject: [PATCH 75/93] Fixed tests, updated pubspec and changelog --- CHANGELOG.md | 2 + pubspec.yaml | 2 +- .../models_generator_test.dart | 117 ++++++++++-------- 3 files changed, 65 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e5f0678..0e954bcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ * ***Breaking*** Added ability to rename downloaded swagger files ([#558](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/558)) +* Added support of deprecated fields and methods ([#699](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/699)) + # 2.13.5 * Added `ErrorConverter` to create method diff --git a/pubspec.yaml b/pubspec.yaml index 3063e3ac..a6d39907 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.13.5 +version: 2.14.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 diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index c93d4190..fea9c3e0 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -161,11 +161,12 @@ void main() { const propertyName = 'shipDate'; const jsonKeyExpendedResult = "@JsonKey(name: '$propertyName'"; final result = generator.generatePropertyContentByDefault( - propertyEntryMap, - propertyName, - [], - [], - [], + prop: propertyEntryMap, + propertyName: propertyName, + allEnumNames: [], + allEnumListNames: [], + requiredProperties: [], + isDeprecated: false, ); expect(result, contains(jsonKeyExpendedResult)); @@ -179,11 +180,12 @@ void main() { outputFolder: '', includeIfNull: false, )).generatePropertyContentByDefault( - propertyEntryMap, - propertyName, - [], - [], - [], + prop: propertyEntryMap, + propertyName: propertyName, + allEnumNames: [], + allEnumListNames: [], + requiredProperties: [], + isDeprecated: false, ); expect(result, contains(', includeIfNull: false')); @@ -193,11 +195,12 @@ void main() { final propertyEntryMap = SwaggerSchema(originalRef: 'Pet'); const propertyName = 'shipDate'; final result = generator.generatePropertyContentByDefault( - propertyEntryMap, - propertyName, - [], - [], - [], + prop: propertyEntryMap, + propertyName: propertyName, + allEnumNames: [], + allEnumListNames: [], + requiredProperties: [], + isDeprecated: false, ); expect(result.contains(', includeIfNull: false'), equals(false)); @@ -422,16 +425,17 @@ void main() { const propertyExpectedResult = 'final List? dog'; final result = generator.generateListPropertyContent( - propertyName, - propertyKey, - className, - map, - [], - [], - [], - {}, - [], - {}, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + prop: map, + classesWithNullableLists: [], + allEnumNames: [], + allEnumListNames: [], + basicTypesMap: {}, + requiredProperties: [], + allClasses: {}, + isDeprecated: false, ); expect(result, contains(jsonKeyExpectedResult)); @@ -444,16 +448,17 @@ void main() { const className = 'Animals'; const propertyKey = 'Dog'; final result = generator.generateListPropertyContent( - propertyName, - propertyKey, - className, - map, - [], - ['Dog'], - [], - {}, - [], - {}, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + prop: map, + classesWithNullableLists: [], + allEnumNames: [], + allEnumListNames: [], + basicTypesMap: {}, + requiredProperties: [], + allClasses: {}, + isDeprecated: false, ); expect( @@ -468,16 +473,17 @@ void main() { const propertyKey = 'Dog'; final result = generator.generateListPropertyContent( - propertyName, - propertyKey, - className, - map, - [], - [], - [], - {}, - [], - {}, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + prop: map, + classesWithNullableLists: [], + allEnumNames: [], + allEnumListNames: [], + basicTypesMap: {}, + requiredProperties: [], + allClasses: {}, + isDeprecated: false, ); expect(result, contains('final List? dog;')); @@ -491,16 +497,17 @@ void main() { const propertyKey = 'Dog'; final result = generator.generateListPropertyContent( - propertyName, - propertyKey, - className, - map, - [], - [], - [], - {}, - [], - {}, + propertyName: propertyName, + propertyKey: propertyKey, + className: className, + prop: map, + classesWithNullableLists: [], + allEnumNames: [], + allEnumListNames: [], + basicTypesMap: {}, + requiredProperties: [], + allClasses: {}, + isDeprecated: false, ); expect(result, contains('final List? dog;')); From eeacf5edd9e451539731be125266856fa4536776 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Dec 2023 13:30:46 +0300 Subject: [PATCH 76/93] Fixed putIfAbsent for allOf schemas #700 --- 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 09a141d7..10101d58 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -362,6 +362,9 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } else if (successResponse?.content?.schema?.properties.isNotEmpty == true) { results.add(response); + } else if (successResponse?.content?.schema?.allOf.isNotEmpty == true && + successResponse?.content?.schema?.title.isNotEmpty == true) { + results.add(response); } return results.where((element) => _isValidModelName(element)).toList(); From 2c518e4911ab6e897f232eea923b7237887e8c34 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 29 Dec 2023 13:44:42 +0300 Subject: [PATCH 77/93] Fixed tests --- test/generator_tests/models_generator_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/generator_tests/models_generator_test.dart b/test/generator_tests/models_generator_test.dart index fea9c3e0..7663d7c6 100644 --- a/test/generator_tests/models_generator_test.dart +++ b/test/generator_tests/models_generator_test.dart @@ -453,7 +453,7 @@ void main() { className: className, prop: map, classesWithNullableLists: [], - allEnumNames: [], + allEnumNames: ['Dog'], allEnumListNames: [], basicTypesMap: {}, requiredProperties: [], From b3bf10e58622c75cace309a7c95a0b11c70efd63 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 5 Jan 2024 10:53:31 +0300 Subject: [PATCH 78/93] Implemented new build option --- example/input_folder/some_file_name.json | 1037 +--------------- .../pet_service_json.swagger.dart | 1047 ----------------- .../pet_service_swagger.swagger.dart | 2 + .../pet_service_yaml.swagger.dart | 2 + .../some_file_name.swagger.dart | 2 + .../swagger_enums_generator.dart | 23 +- .../swagger_requests_generator.dart | 82 +- lib/src/models/generator_options.dart | 4 + lib/src/models/generator_options.g2.dart | 3 + 9 files changed, 73 insertions(+), 2129 deletions(-) delete mode 100644 example/lib/swagger_generated_code/pet_service_json.swagger.dart diff --git a/example/input_folder/some_file_name.json b/example/input_folder/some_file_name.json index ca1a8f69..1becba2b 100644 --- a/example/input_folder/some_file_name.json +++ b/example/input_folder/some_file_name.json @@ -1,1036 +1 @@ -{ - "swagger": "2.0", - "info": { - "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", - "version": "1.0.0", - "title": "Swagger Petstore", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "email": "apiteam@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "host": "petstore.swagger.io", - "basePath": "/v2", - "tags": [ - { - "name": "pet", - "description": "Everything about your Pets", - "externalDocs": { - "description": "Find out more", - "url": "http://swagger.io" - } - }, - { - "name": "store", - "description": "Access to Petstore orders" - }, - { - "name": "user", - "description": "Operations about user", - "externalDocs": { - "description": "Find out more about our store", - "url": "http://swagger.io" - } - } - ], - "schemes": [ - "https", - "http" - ], - "paths": { - "/pet": { - "post": { - "tags": [ - "pet" - ], - "summary": "Add a new pet to the store", - "description": "", - "operationId": "addPet", - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "schema": { - "$ref": "#/definitions/Pet" - } - } - ], - "responses": { - "405": { - "description": "Invalid input" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - }, - "put": { - "tags": [ - "pet" - ], - "summary": "Update an existing pet", - "description": "", - "operationId": "updatePet", - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "schema": { - "$ref": "#/definitions/Pet" - } - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - }, - "405": { - "description": "Validation exception" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/findByStatus": { - "get": { - "tags": [ - "pet" - ], - "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma separated strings", - "operationId": "findPetsByStatus", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "status", - "in": "query", - "description": "Status values that need to be considered for filter", - "required": true, - "type": "array", - "items": { - "type": "string", - "enum": [ - "available", - "pending", - "sold" - ], - "default": "available" - }, - "collectionFormat": "multi" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid status value" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/findByTags": { - "get": { - "tags": [ - "pet" - ], - "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId": "findPetsByTags", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "Tags to filter by", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "multi" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid tag value" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ], - "deprecated": true - } - }, - "/pet/{petId}": { - "get": { - "tags": [ - "pet" - ], - "summary": "Find pet by ID", - "description": "Returns a single pet", - "operationId": "getPetById", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet to return", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - } - }, - "security": [ - { - "api_key": [] - } - ] - }, - "post": { - "tags": [ - "pet" - ], - "summary": "Updates a pet in the store with form data", - "description": "", - "operationId": "updatePetWithForm", - "consumes": [ - "application/x-www-form-urlencoded" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be updated", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "name", - "in": "formData", - "description": "Updated name of the pet", - "required": false, - "type": "string" - }, - { - "name": "status", - "in": "formData", - "description": "Updated status of the pet", - "required": false, - "type": "string" - } - ], - "responses": { - "405": { - "description": "Invalid input" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - }, - "delete": { - "tags": [ - "pet" - ], - "summary": "Deletes a pet", - "description": "", - "operationId": "deletePet", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "api_key", - "in": "header", - "required": false, - "type": "string" - }, - { - "name": "petId", - "in": "path", - "description": "Pet id to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/{petId}/uploadImage": { - "post": { - "tags": [ - "pet" - ], - "summary": "uploads an image", - "description": "", - "operationId": "uploadFile", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet to update", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "additionalMetadata", - "in": "formData", - "description": "Additional data to pass to server", - "required": false, - "type": "string" - }, - { - "name": "file", - "in": "formData", - "description": "file to upload", - "required": false, - "type": "file" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/ApiResponse" - } - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/store/inventory": { - "get": { - "tags": [ - "store" - ], - "summary": "Returns pet inventories by status", - "description": "Returns a map of status codes to quantities", - "operationId": "getInventory", - "produces": [ - "application/json" - ], - "parameters": [], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "object", - "additionalProperties": { - "type": "integer", - "format": "int32" - } - } - } - }, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/store/order": { - "post": { - "tags": [ - "store" - ], - "summary": "Place an order for a pet", - "description": "", - "operationId": "placeOrder", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "order placed for purchasing the pet", - "required": true, - "schema": { - "$ref": "#/definitions/Order" - } - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Order" - } - }, - "400": { - "description": "Invalid Order" - } - } - } - }, - "/store/order/{orderId}": { - "get": { - "tags": [ - "store" - ], - "summary": "Find purchase order by ID", - "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", - "operationId": "getOrderById", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "orderId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "maximum": 10, - "minimum": 1, - "format": "int64" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Order" - } - }, - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Order not found" - } - } - }, - "delete": { - "tags": [ - "store" - ], - "summary": "Delete purchase order by ID", - "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", - "operationId": "deleteOrder", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "orderId", - "in": "path", - "description": "ID of the order that needs to be deleted", - "required": true, - "type": "integer", - "minimum": 1, - "format": "int64" - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Order not found" - } - } - } - }, - "/user": { - "post": { - "tags": [ - "user" - ], - "summary": "Create user", - "description": "This can only be done by the logged in user.", - "operationId": "createUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Created user object", - "required": true, - "schema": { - "$ref": "#/definitions/User" - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/createWithArray": { - "post": { - "tags": [ - "user" - ], - "summary": "Creates list of users with given input array", - "description": "", - "operationId": "createUsersWithArrayInput", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "List of user object", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/User" - } - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/createWithList": { - "post": { - "tags": [ - "user" - ], - "summary": "Creates list of users with given input array", - "description": "", - "operationId": "createUsersWithListInput", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "List of user object", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/User" - } - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/login": { - "get": { - "tags": [ - "user" - ], - "summary": "Logs user into the system", - "description": "", - "operationId": "loginUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "query", - "description": "The user name for login", - "required": true, - "type": "string" - }, - { - "name": "password", - "in": "query", - "description": "The password for login in clear text", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "string" - }, - "headers": { - "X-Rate-Limit": { - "type": "integer", - "format": "int32", - "description": "calls per hour allowed by the user" - }, - "X-Expires-After": { - "type": "string", - "format": "date-time", - "description": "date in UTC when token expires" - } - } - }, - "400": { - "description": "Invalid username/password supplied" - } - } - } - }, - "/user/logout": { - "get": { - "tags": [ - "user" - ], - "summary": "Logs out current logged in user session", - "description": "", - "operationId": "logoutUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/{username}": { - "get": { - "tags": [ - "user" - ], - "summary": "Get user by user name", - "description": "", - "operationId": "getUserByName", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "The name that needs to be fetched. Use user1 for testing. ", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/User" - } - }, - "400": { - "description": "Invalid username supplied" - }, - "404": { - "description": "User not found" - } - } - }, - "put": { - "tags": [ - "user" - ], - "summary": "Updated user", - "description": "This can only be done by the logged in user.", - "operationId": "updateUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "name that need to be updated", - "required": true, - "type": "string" - }, - { - "in": "body", - "name": "body", - "description": "Updated user object", - "required": true, - "schema": { - "$ref": "#/definitions/User" - } - } - ], - "responses": { - "400": { - "description": "Invalid user supplied" - }, - "404": { - "description": "User not found" - } - } - }, - "delete": { - "tags": [ - "user" - ], - "summary": "Delete user", - "description": "This can only be done by the logged in user.", - "operationId": "deleteUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "The name that needs to be deleted", - "required": true, - "type": "string" - } - ], - "responses": { - "400": { - "description": "Invalid username supplied" - }, - "404": { - "description": "User not found" - } - } - } - } - }, - "securityDefinitions": { - "petstore_auth": { - "type": "oauth2", - "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", - "flow": "implicit", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - }, - "api_key": { - "type": "apiKey", - "name": "api_key", - "in": "header" - } - }, - "definitions": { - "Order": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "petId": { - "type": "integer", - "format": "int64" - }, - "quantity": { - "type": "integer", - "format": "int32" - }, - "shipDate": { - "type": "string", - "format": "date-time" - }, - "status": { - "type": "string", - "description": "Order Status", - "enum": [ - "placed", - "approved", - "delivered" - ] - }, - "complete": { - "type": "boolean", - "default": false - } - }, - "xml": { - "name": "Order" - } - }, - "Category": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Category" - } - }, - "User": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "username": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "email": { - "type": "string" - }, - "password": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "userStatus": { - "type": "integer", - "format": "int32", - "description": "User Status" - } - }, - "xml": { - "name": "User" - } - }, - "Tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Tag" - } - }, - "Pet": { - "type": "object", - "required": [ - "name", - "photoUrls" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "category": { - "$ref": "#/definitions/Category" - }, - "name": { - "type": "string", - "example": "doggie" - }, - "photoUrls": { - "type": "array", - "xml": { - "name": "photoUrl", - "wrapped": true - }, - "items": { - "type": "string" - } - }, - "tags": { - "type": "array", - "xml": { - "name": "tag", - "wrapped": true - }, - "items": { - "$ref": "#/definitions/Tag" - } - }, - "status": { - "type": "string", - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ] - } - }, - "xml": { - "name": "Pet" - } - }, - "ApiResponse": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "type": { - "type": "string" - }, - "message": { - "type": "string" - } - } - } - }, - "externalDocs": { - "description": "Find out more about Swagger", - "url": "http://swagger.io" - } -} \ No newline at end of file +404: Not Found \ No newline at end of file diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.dart b/example/lib/swagger_generated_code/pet_service_json.swagger.dart deleted file mode 100644 index 1a51d210..00000000 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.dart +++ /dev/null @@ -1,1047 +0,0 @@ -// ignore_for_file: type=lint - -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_json.enums.swagger.dart' as enums; -export 'pet_service_json.enums.swagger.dart'; - -part 'pet_service_json.swagger.chopper.dart'; -part 'pet_service_json.swagger.g.dart'; - -// ************************************************************************** -// SwaggerChopperGenerator -// ************************************************************************** - -@ChopperApi() -abstract class PetServiceJson extends ChopperService { - static PetServiceJson create({ - ChopperClient? client, - http.Client? httpClient, - Authenticator? authenticator, - ErrorConverter? errorConverter, - Converter? converter, - Uri? baseUrl, - Iterable? interceptors, - }) { - if (client != null) { - return _$PetServiceJson(client); - } - - final newClient = ChopperClient( - services: [_$PetServiceJson()], - converter: converter ?? $JsonSerializableConverter(), - interceptors: interceptors ?? [], - client: httpClient, - authenticator: authenticator, - errorConverter: errorConverter, - baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); - return _$PetServiceJson(newClient); - } - - ///Add a new pet to the store - ///@param body Pet object that needs to be added to the store - Future petPost({ - required Pet? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Add a new pet to the store - ///@param body Pet object that needs to be added to the store - @Post(path: '/pet') - Future _petPost({ - @Body() required Pet? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Update an existing pet - ///@param body Pet object that needs to be added to the store - Future petPut({ - required Pet? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPut(body: body, cacheControl: cacheControl?.toString()); - } - - ///Update an existing pet - ///@param body Pet object that needs to be added to the store - @Put(path: '/pet') - Future _petPut({ - @Body() required Pet? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Finds Pets by status - ///@param status Status values that need to be considered for filter - Future>> petFindByStatusGet({ - required List? status, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petFindByStatusGet( - 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 List? status, - @Header('Cache-Control') String? cacheControl, - }); - - ///Finds Pets by tags - ///@param tags Tags to filter by - Future>> petFindByTagsGet({ - required List? tags, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - 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, - @Header('Cache-Control') String? cacheControl, - }); - - ///Find pet by ID - ///@param petId ID of pet to return - Future> petPetIdGet({ - required int? petId, - dynamic apiKey, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPetIdGet( - petId: petId, - apiKey: apiKey?.toString(), - cacheControl: cacheControl?.toString()); - } - - ///Find pet by ID - ///@param petId ID of pet to return - @Get(path: '/pet/{petId}') - Future> _petPetIdGet({ - @Path('petId') required int? petId, - @Header('api_key') String? apiKey, - @Header('Cache-Control') String? cacheControl, - }); - - ///Updates a pet in the store with form data - ///@param petId ID of pet that needs to be updated - ///@param name Updated name of the pet - ///@param status Updated status of the pet - Future petPetIdPost({ - required int? petId, - String? name, - String? status, - dynamic cacheControl, - }) { - return _petPetIdPost( - petId: petId, - name: name, - status: status, - cacheControl: cacheControl?.toString()); - } - - ///Updates a pet in the store with form data - ///@param petId ID of pet that needs to be updated - ///@param name Updated name of the pet - ///@param status Updated status of the pet - @Post( - path: '/pet/{petId}', - optionalBody: true, - ) - Future _petPetIdPost({ - @Path('petId') required int? petId, - @Field('name') String? name, - @Field('status') String? status, - @Header('Cache-Control') String? cacheControl, - }); - - ///Deletes a pet - ///@param api_key - ///@param petId Pet id to delete - Future petPetIdDelete({ - String? apiKey, - required int? petId, - dynamic cacheControl, - }) { - return _petPetIdDelete( - apiKey: apiKey?.toString(), - petId: petId, - cacheControl: cacheControl?.toString()); - } - - ///Deletes a pet - ///@param api_key - ///@param petId Pet id to delete - @Delete(path: '/pet/{petId}') - Future _petPetIdDelete({ - @Header('api_key') String? apiKey, - @Path('petId') required int? petId, - @Header('Cache-Control') String? cacheControl, - }); - - ///uploads an image - ///@param petId ID of pet to update - ///@param additionalMetadata Additional data to pass to server - ///@param file file to upload - Future> petPetIdUploadImagePost({ - required int? petId, - String? additionalMetadata, - List? file, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent( - ApiResponse, () => ApiResponse.fromJsonFactory); - - return _petPetIdUploadImagePost( - petId: petId, - additionalMetadata: additionalMetadata, - file: file, - cacheControl: cacheControl?.toString()); - } - - ///uploads an image - ///@param petId ID of pet to update - ///@param additionalMetadata Additional data to pass to server - ///@param file file to upload - @Post( - path: '/pet/{petId}/uploadImage', - optionalBody: true, - ) - Future> _petPetIdUploadImagePost({ - @Path('petId') required int? petId, - @Field('additionalMetadata') String? additionalMetadata, - @Field('file') List? file, - @Header('Cache-Control') String? cacheControl, - }); - - ///Returns pet inventories by status - Future> storeInventoryGet({ - dynamic apiKey, - dynamic cacheControl, - }) { - return _storeInventoryGet( - apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); - } - - ///Returns pet inventories by status - @Get(path: '/store/inventory') - Future> _storeInventoryGet({ - @Header('api_key') String? apiKey, - @Header('Cache-Control') String? cacheControl, - }); - - ///Place an order for a pet - ///@param body order placed for purchasing the pet - Future> storeOrderPost({ - required Order? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - - return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Place an order for a pet - ///@param body order placed for purchasing the pet - @Post(path: '/store/order') - Future> _storeOrderPost({ - @Body() required Order? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Find purchase order by ID - ///@param orderId ID of pet that needs to be fetched - Future> storeOrderOrderIdGet({ - required int? orderId, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - - return _storeOrderOrderIdGet( - orderId: orderId, cacheControl: cacheControl?.toString()); - } - - ///Find purchase order by ID - ///@param orderId ID of pet that needs to be fetched - @Get(path: '/store/order/{orderId}') - Future> _storeOrderOrderIdGet({ - @Path('orderId') required int? orderId, - @Header('Cache-Control') String? cacheControl, - }); - - ///Delete purchase order by ID - ///@param orderId ID of the order that needs to be deleted - Future storeOrderOrderIdDelete({ - required int? orderId, - dynamic cacheControl, - }) { - return _storeOrderOrderIdDelete( - orderId: orderId, cacheControl: cacheControl?.toString()); - } - - ///Delete purchase order by ID - ///@param orderId ID of the order that needs to be deleted - @Delete(path: '/store/order/{orderId}') - Future _storeOrderOrderIdDelete({ - @Path('orderId') required int? orderId, - @Header('Cache-Control') String? cacheControl, - }); - - ///Create user - ///@param body Created user object - Future userPost({ - required User? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Create user - ///@param body Created user object - @Post(path: '/user') - Future _userPost({ - @Body() required User? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Creates list of users with given input array - ///@param body List of user object - Future userCreateWithArrayPost({ - required List? body, - dynamic cacheControl, - }) { - return _userCreateWithArrayPost( - body: body, cacheControl: cacheControl?.toString()); - } - - ///Creates list of users with given input array - ///@param body List of user object - @Post(path: '/user/createWithArray') - Future _userCreateWithArrayPost({ - @Body() required List? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Creates list of users with given input array - ///@param body List of user object - Future userCreateWithListPost({ - required List? body, - dynamic cacheControl, - }) { - return _userCreateWithListPost( - body: body, cacheControl: cacheControl?.toString()); - } - - ///Creates list of users with given input array - ///@param body List of user object - @Post(path: '/user/createWithList') - Future _userCreateWithListPost({ - @Body() required List? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Logs user into the system - ///@param username The user name for login - ///@param password The password for login in clear text - Future> userLoginGet({ - required String? username, - required String? password, - dynamic cacheControl, - }) { - return _userLoginGet( - username: username, - password: password, - cacheControl: cacheControl?.toString()); - } - - ///Logs user into the system - ///@param username The user name for login - ///@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, - @Header('Cache-Control') String? cacheControl, - }); - - ///Logs out current logged in user session - Future userLogoutGet({dynamic cacheControl}) { - return _userLogoutGet(cacheControl: cacheControl?.toString()); - } - - ///Logs out current logged in user session - @Get(path: '/user/logout') - Future _userLogoutGet( - {@Header('Cache-Control') String? cacheControl}); - - ///Get user by user name - ///@param username The name that needs to be fetched. Use user1 for testing. - Future> userUsernameGet({ - required String? username, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userUsernameGet( - username: username, cacheControl: cacheControl?.toString()); - } - - ///Get user by user name - ///@param username The name that needs to be fetched. Use user1 for testing. - @Get(path: '/user/{username}') - Future> _userUsernameGet({ - @Path('username') required String? username, - @Header('Cache-Control') String? cacheControl, - }); - - ///Updated user - ///@param username name that need to be updated - ///@param body Updated user object - Future userUsernamePut({ - required String? username, - required User? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userUsernamePut( - username: username, body: body, cacheControl: cacheControl?.toString()); - } - - ///Updated user - ///@param username name that need to be updated - ///@param body Updated user object - @Put(path: '/user/{username}') - Future _userUsernamePut({ - @Path('username') required String? username, - @Body() required User? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Delete user - ///@param username The name that needs to be deleted - Future userUsernameDelete({ - required String? username, - dynamic cacheControl, - }) { - return _userUsernameDelete( - username: username, cacheControl: cacheControl?.toString()); - } - - ///Delete user - ///@param username The name that needs to be deleted - @Delete(path: '/user/{username}') - Future _userUsernameDelete({ - @Path('username') required String? username, - @Header('Cache-Control') String? cacheControl, - }); -} - -@JsonSerializable(explicitToJson: true) -class Category { - const Category({ - this.id, - this.name, - }); - - factory Category.fromJson(Map json) => - _$CategoryFromJson(json); - - static const toJsonFactory = _$CategoryToJson; - Map toJson() => _$CategoryToJson(this); - - @JsonKey(name: 'id', includeIfNull: false) - final int? id; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$CategoryFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Category && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $CategoryExtension on Category { - Category copyWith({int? id, String? name}) { - return Category(id: id ?? this.id, name: name ?? this.name); - } - - Category copyWithWrapped({Wrapped? id, Wrapped? name}) { - return Category( - id: (id != null ? id.value : this.id), - name: (name != null ? name.value : this.name)); - } -} - -@JsonSerializable(explicitToJson: true) -class User { - const User({ - this.id, - this.username, - this.firstName, - this.lastName, - this.email, - this.password, - this.phone, - this.userStatus, - }); - - factory User.fromJson(Map json) => _$UserFromJson(json); - - static const toJsonFactory = _$UserToJson; - Map toJson() => _$UserToJson(this); - - @JsonKey(name: 'id', includeIfNull: false) - final int? id; - @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') - final String? username; - @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') - final String? firstName; - @JsonKey(name: 'lastName', includeIfNull: false, defaultValue: '') - final String? lastName; - @JsonKey(name: 'email', includeIfNull: false, defaultValue: '') - final String? email; - @JsonKey(name: 'password', includeIfNull: false, defaultValue: '') - final String? password; - @JsonKey(name: 'phone', includeIfNull: false, defaultValue: '') - final String? phone; - @JsonKey(name: 'userStatus', includeIfNull: false) - final int? userStatus; - static const fromJsonFactory = _$UserFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is User && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.username, username) || - const DeepCollectionEquality() - .equals(other.username, username)) && - (identical(other.firstName, firstName) || - const DeepCollectionEquality() - .equals(other.firstName, firstName)) && - (identical(other.lastName, lastName) || - const DeepCollectionEquality() - .equals(other.lastName, lastName)) && - (identical(other.email, email) || - const DeepCollectionEquality().equals(other.email, email)) && - (identical(other.password, password) || - const DeepCollectionEquality() - .equals(other.password, password)) && - (identical(other.phone, phone) || - const DeepCollectionEquality().equals(other.phone, phone)) && - (identical(other.userStatus, userStatus) || - const DeepCollectionEquality() - .equals(other.userStatus, userStatus))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(username) ^ - const DeepCollectionEquality().hash(firstName) ^ - const DeepCollectionEquality().hash(lastName) ^ - const DeepCollectionEquality().hash(email) ^ - const DeepCollectionEquality().hash(password) ^ - const DeepCollectionEquality().hash(phone) ^ - const DeepCollectionEquality().hash(userStatus) ^ - runtimeType.hashCode; -} - -extension $UserExtension on User { - User copyWith( - {int? id, - String? username, - String? firstName, - String? lastName, - String? email, - String? password, - String? phone, - int? userStatus}) { - return User( - id: id ?? this.id, - username: username ?? this.username, - firstName: firstName ?? this.firstName, - lastName: lastName ?? this.lastName, - email: email ?? this.email, - password: password ?? this.password, - phone: phone ?? this.phone, - userStatus: userStatus ?? this.userStatus); - } - - User copyWithWrapped( - {Wrapped? id, - Wrapped? username, - Wrapped? firstName, - Wrapped? lastName, - Wrapped? email, - Wrapped? password, - Wrapped? phone, - Wrapped? userStatus}) { - return User( - id: (id != null ? id.value : this.id), - username: (username != null ? username.value : this.username), - firstName: (firstName != null ? firstName.value : this.firstName), - lastName: (lastName != null ? lastName.value : this.lastName), - email: (email != null ? email.value : this.email), - password: (password != null ? password.value : this.password), - phone: (phone != null ? phone.value : this.phone), - userStatus: (userStatus != null ? userStatus.value : this.userStatus)); - } -} - -@JsonSerializable(explicitToJson: true) -class 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 int? id; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$TagFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Tag && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $TagExtension on Tag { - Tag copyWith({int? id, String? name}) { - return Tag(id: id ?? this.id, name: name ?? this.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 ApiResponse { - const ApiResponse({ - this.code, - this.type, - this.message, - }); - - 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: '') - final String? type; - @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') - final String? message; - static const fromJsonFactory = _$ApiResponseFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is ApiResponse && - (identical(other.code, code) || - const DeepCollectionEquality().equals(other.code, code)) && - (identical(other.type, type) || - const DeepCollectionEquality().equals(other.type, type)) && - (identical(other.message, message) || - const DeepCollectionEquality().equals(other.message, message))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(code) ^ - const DeepCollectionEquality().hash(type) ^ - const DeepCollectionEquality().hash(message) ^ - runtimeType.hashCode; -} - -extension $ApiResponseExtension on ApiResponse { - ApiResponse copyWith({int? code, String? type, String? message}) { - return ApiResponse( - code: code ?? this.code, - type: type ?? this.type, - message: message ?? this.message); - } - - ApiResponse copyWithWrapped( - {Wrapped? code, - Wrapped? type, - Wrapped? message}) { - return ApiResponse( - code: (code != null ? code.value : this.code), - type: (type != null ? type.value : this.type), - message: (message != null ? message.value : this.message)); - } -} - -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.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 []; - } - - return orderStatus.map((e) => e.value!).toList(); -} - -List orderStatusListFromJson( - List? orderStatus, [ - List? defaultValue, -]) { - if (orderStatus == null) { - return defaultValue ?? []; - } - - return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); -} - -List? orderStatusNullableListFromJson( - List? orderStatus, [ - List? defaultValue, -]) { - if (orderStatus == null) { - return defaultValue; - } - - return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); -} - -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.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 []; - } - - return petStatus.map((e) => e.value!).toList(); -} - -List petStatusListFromJson( - List? petStatus, [ - List? defaultValue, -]) { - if (petStatus == null) { - return defaultValue ?? []; - } - - return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); -} - -List? petStatusNullableListFromJson( - List? petStatus, [ - List? defaultValue, -]) { - if (petStatus == null) { - return defaultValue; - } - - return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); -} - -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.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) { - return []; - } - - return petFindByStatusGetStatus.map((e) => e.value!).toList(); -} - -List petFindByStatusGetStatusListFromJson( - List? petFindByStatusGetStatus, [ - List? defaultValue, -]) { - if (petFindByStatusGetStatus == null) { - return defaultValue ?? []; - } - - return petFindByStatusGetStatus - .map((e) => petFindByStatusGetStatusFromJson(e.toString())) - .toList(); -} - -List? - petFindByStatusGetStatusNullableListFromJson( - List? petFindByStatusGetStatus, [ - List? defaultValue, -]) { - if (petFindByStatusGetStatus == null) { - return defaultValue; - } - - return petFindByStatusGetStatus - .map((e) => petFindByStatusGetStatusFromJson(e.toString())) - .toList(); -} - -typedef $JsonFactory = T Function(Map json); - -class $CustomJsonDecoder { - $CustomJsonDecoder(this.factories); - - final Map factories; - - dynamic decode(dynamic entity) { - if (entity is Iterable) { - return _decodeList(entity); - } - - if (entity is T) { - return entity; - } - - if (isTypeOf()) { - return entity; - } - - if (isTypeOf()) { - return entity; - } - - if (entity is Map) { - return _decodeMap(entity); - } - - return entity; - } - - T _decodeMap(Map values) { - final jsonFactory = factories[T]; - if (jsonFactory == null || jsonFactory is! $JsonFactory) { - return throw "Could not find factory for type $T. Is '$T: $T.fromJsonFactory' included in the CustomJsonDecoder instance creation in bootstrapper.dart?"; - } - - return jsonFactory(values); - } - - List _decodeList(Iterable values) => - values.where((v) => v != null).map((v) => decode(v) as T).toList(); -} - -class $JsonSerializableConverter extends chopper.JsonConverter { - @override - FutureOr> convertResponse( - chopper.Response response) async { - if (response.bodyString.isEmpty) { - // In rare cases, when let's say 204 (no content) is returned - - // we cannot decode the missing json with the result type specified - return chopper.Response(response.base, null, error: response.error); - } - - 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); - } -} - -final $jsonDecoder = $CustomJsonDecoder(generatedMapping); - -// ignore: unused_element -String? _dateToJson(DateTime? date) { - if (date == null) { - return null; - } - - final year = date.year.toString(); - final month = date.month < 10 ? '0${date.month}' : date.month.toString(); - final day = date.day < 10 ? '0${date.day}' : date.day.toString(); - - return '$year-$month-$day'; -} - -class Wrapped { - final T value; - const Wrapped.value(this.value); -} 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 263cc308..d4f90f5d 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart @@ -108,6 +108,7 @@ abstract class PetServiceSwagger extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class PetServiceSwagger extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, 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 8c7565c6..fe321815 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart @@ -108,6 +108,7 @@ abstract class PetServiceYaml extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class PetServiceYaml extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, diff --git a/example/lib/swagger_generated_code/some_file_name.swagger.dart b/example/lib/swagger_generated_code/some_file_name.swagger.dart index e222bfc9..3777b6d3 100644 --- a/example/lib/swagger_generated_code/some_file_name.swagger.dart +++ b/example/lib/swagger_generated_code/some_file_name.swagger.dart @@ -108,6 +108,7 @@ abstract class SomeFileName extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class SomeFileName extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index acd0ae12..cc7fe650 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -156,17 +156,20 @@ ${allEnums.map((e) => e.toString()).join('\n')} swaggerRoot.paths.forEach((String path, SwaggerPath swaggerPath) { swaggerPath.requests .forEach((String requestType, SwaggerRequest swaggerRequest) { - final successResponse = SwaggerRequestsGenerator.getSuccessedResponse( + final successResponses = SwaggerRequestsGenerator.getSuccessedResponses( responses: swaggerRequest.responses); - final successResponseSchema = - successResponse?.schema ?? successResponse?.content?.schema; - - if (successResponseSchema != null) { - final responseEnums = generateEnumsFromSchemaMap({ - '${path.pascalCase}${requestType.pascalCase}\$$kResponse': - successResponseSchema - }); - result.addAll(responseEnums); + + for (final successResponse in successResponses) { + final successResponseSchema = + successResponse.schema ?? successResponse.content?.schema; + + if (successResponseSchema != null) { + final responseEnums = generateEnumsFromSchemaMap({ + '${path.pascalCase}${requestType.pascalCase}\$$kResponse': + successResponseSchema + }); + result.addAll(responseEnums); + } } final parameters = [ diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 10101d58..2b41e63b 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -325,46 +325,49 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } } - //Models from response - final successResponse = getSuccessedResponse(responses: request.responses); - final responseRef = successResponse?.anyRef ?? ''; + //Models from responses + final successResponses = + getSuccessedResponses(responses: request.responses); + for (final successResponse in successResponses) { + final responseRef = successResponse.anyRef; - if (responseRef.isNotEmpty) { - final schema = root.allSchemas[responseRef.getUnformattedRef()]; + if (responseRef.isNotEmpty) { + final schema = root.allSchemas[responseRef.getUnformattedRef()]; - if (schema?.type == kArray) { - if (schema?.items?.ref.isNotEmpty == true) { - final ref = schema!.items!.ref; - final itemType = getValidatedClassName(ref.getUnformattedRef()); - results.add(itemType); - } else { - final itemsType = schema?.items?.type; + if (schema?.type == kArray) { + if (schema?.items?.ref.isNotEmpty == true) { + final ref = schema!.items!.ref; + final itemType = getValidatedClassName(ref.getUnformattedRef()); + results.add(itemType); + } else { + final itemsType = schema?.items?.type; - if (!kBasicTypes.contains(itemsType) && - schema?.items?.properties != null) { - final itemClassName = '$response\$Item'; + if (!kBasicTypes.contains(itemsType) && + schema?.items?.properties != null) { + final itemClassName = '$response\$Item'; - results.add(itemClassName); + results.add(itemClassName); + } } - } - } else { - if (!response.startsWith('$kMap<')) { - final neededResponse = response.removeListOrStream(); + } else { + if (!response.startsWith('$kMap<')) { + final neededResponse = response.removeListOrStream(); - if (!kBasicTypes.contains(neededResponse) && - neededResponse != kDynamic) { - results.add(getValidatedClassName(neededResponse)); + if (!kBasicTypes.contains(neededResponse) && + neededResponse != kDynamic) { + results.add(getValidatedClassName(neededResponse)); + } } } + } else if (successResponse.schema?.properties.isNotEmpty == true) { + results.add(response); + } else if (successResponse.content?.schema?.properties.isNotEmpty == + true) { + results.add(response); + } else if (successResponse.content?.schema?.allOf.isNotEmpty == true && + successResponse.content?.schema?.title.isNotEmpty == true) { + results.add(response); } - } else if (successResponse?.schema?.properties.isNotEmpty == true) { - results.add(response); - } else if (successResponse?.content?.schema?.properties.isNotEmpty == - true) { - results.add(response); - } else if (successResponse?.content?.schema?.allOf.isNotEmpty == true && - successResponse?.content?.schema?.title.isNotEmpty == true) { - results.add(response); } return results.where((element) => _isValidModelName(element)).toList(); @@ -1108,14 +1111,15 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return methodName; } - static SwaggerResponse? getSuccessedResponse({ + static List getSuccessedResponses({ required Map responses, }) { return responses.entries - .firstWhereOrNull((responseEntry) => + .where((responseEntry) => successResponseCodes.contains(responseEntry.key) || successDescriptions.contains(responseEntry.value.description)) - ?.value; + .map((e) => e.value) + .toList(); } String _getResponseModelName({ @@ -1349,14 +1353,20 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return overridenResponses[path]!.overriddenValue; } - final neededResponse = getSuccessedResponse( + final neededResponses = getSuccessedResponses( responses: responses, ); - if (neededResponse == null) { + if (neededResponses.isEmpty) { return ''; } + if (neededResponses.length > 1 && !options.generateFirstSucceedResponse) { + return ''; + } + + final neededResponse = neededResponses.first; + if (neededResponse.schema?.type == kObject && neededResponse.schema?.properties.isNotEmpty == true) { return _getResponseModelName( diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 997dcee4..a96971d7 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -38,6 +38,7 @@ class GeneratorOptions { this.generateToJsonFor = const [], this.multipartFileType = 'List', this.urlencodedFileType = 'Map', + this.generateFirstSucceedResponse = true, }); /// Build options from a JSON map. @@ -47,6 +48,9 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool usePathForRequestNames; + @JsonKey(defaultValue: true) + final bool generateFirstSucceedResponse; + @JsonKey(defaultValue: true) final bool withBaseUrl; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 4a532b2b..a6d8bbcb 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -88,6 +88,8 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( multipartFileType: json['multipart_file_type'] as String? ?? 'List', urlencodedFileType: json['urlencoded_file_type'] as String? ?? 'Map', + generateFirstSucceedResponse: + json['generate_first_succeed_response'] as bool? ?? true, ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => @@ -125,6 +127,7 @@ Map _$GeneratorOptionsToJson(GeneratorOptions instance) => 'import_paths': instance.importPaths, 'custom_return_type': instance.customReturnType, 'exclude_paths': instance.excludePaths, + 'generate_first_succeed_response': instance.generateFirstSucceedResponse, }; DefaultValueMap _$DefaultValueMapFromJson(Map json) => From 75d248d8bb4513e68c26d62c32cd9d2ee84e9b30 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 5 Jan 2024 10:55:11 +0300 Subject: [PATCH 79/93] Some fixes --- example/input_folder/pet_service_json.json | 1036 ++++++++++++++++++++ 1 file changed, 1036 insertions(+) create mode 100644 example/input_folder/pet_service_json.json diff --git a/example/input_folder/pet_service_json.json b/example/input_folder/pet_service_json.json new file mode 100644 index 00000000..1c5db9ab --- /dev/null +++ b/example/input_folder/pet_service_json.json @@ -0,0 +1,1036 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "tags": [ + { + "name": "pet", + "description": "Everything about your Pets", + "externalDocs": { + "description": "Find out more", + "url": "http://swagger.io" + } + }, + { + "name": "store", + "description": "Access to Petstore orders" + }, + { + "name": "user", + "description": "Operations about user", + "externalDocs": { + "description": "Find out more about our store", + "url": "http://swagger.io" + } + } + ], + "schemes": [ + "https", + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma separated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": true, + "type": "array", + "items": { + "type": "string", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ], + "deprecated": true + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 10, + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "integer", + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be updated", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Pet": { + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } +} \ No newline at end of file From 99e919296500ef43315fd8b69f90f94643697035 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 5 Jan 2024 11:00:36 +0300 Subject: [PATCH 80/93] Implemented new generator option --- lib/src/code_generators/constants.dart | 6 ------ lib/src/code_generators/swagger_requests_generator.dart | 9 ++++++--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 473eea5b..f42dbcdc 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -1,9 +1,3 @@ -const List successResponseCodes = [ - '200', - '201', - '202', -]; - const List kKeyClasses = [ 'Response', 'Request', diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 2b41e63b..3f125a0d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -1115,9 +1115,12 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required Map responses, }) { return responses.entries - .where((responseEntry) => - successResponseCodes.contains(responseEntry.key) || - successDescriptions.contains(responseEntry.value.description)) + .where((responseEntry) { + final code = int.tryParse(responseEntry.key) ?? 0; + + return code ~/ 100 == 2 || + successDescriptions.contains(responseEntry.value.description); + }) .map((e) => e.value) .toList(); } From 8d0ef5214546a8e65d01cd6b899e862f2d551913 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 5 Jan 2024 11:03:43 +0300 Subject: [PATCH 81/93] Updated changelog, readme and pubspec --- CHANGELOG.md | 4 ++++ README.md | 1 + pubspec.yaml | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e954bcc..eefda9b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.14.2 + +* Added option `generate_first_succeed_response` to generate first succeed response or `dynamic` ([#703](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/703)) + # 2.14.1 * ***Breaking*** Added ability to rename downloaded swagger files ([#558](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/558)) diff --git a/README.md b/README.md index 36b32d1c..4d178e6c 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ targets: | `add_base_path_to_requests` | `false` | `false` | Add swagger base path to all request path. | | `multipart_file_type` | `List` | `false` | Allow to override the generated class for multipart file (See #605). | | `override_to_string` | `bool` | `true` | Overrides `toString()` method using `jsonEncode(this)` | +| `generate_first_succeed_response` | `bool` | `true` | If request has multiple success responses, first one will be generated. Otherwice - `dynamic` | diff --git a/pubspec.yaml b/pubspec.yaml index a6d39907..b54409e4 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.14.1 +version: 2.14.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 3bae56f41651e564aa61b41d4e4aaff7bc0067d7 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Fri, 5 Jan 2024 11:08:11 +0300 Subject: [PATCH 82/93] Fixed conflicts --- .../code_generators/swagger_requests_generator.dart | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index eae48c8d..3f125a0d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -368,17 +368,6 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { successResponse.content?.schema?.title.isNotEmpty == true) { results.add(response); } -<<<<<<< HEAD -======= - } else if (successResponse?.schema?.properties.isNotEmpty == true) { - results.add(response); - } else if (successResponse?.content?.schema?.properties.isNotEmpty == - true) { - results.add(response); - } else if (successResponse?.content?.schema?.allOf.isNotEmpty == true && - successResponse?.content?.schema?.title.isNotEmpty == true) { - results.add(response); ->>>>>>> master } return results.where((element) => _isValidModelName(element)).toList(); From 2b57fc10711cc2752d87ed49e59004400b02b63b Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 23 Jan 2024 14:47:40 +0300 Subject: [PATCH 83/93] Fixed generation of requestBody when one oneOf provided --- lib/src/code_generators/swagger_requests_generator.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 3f125a0d..7139513b 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -960,7 +960,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final schema = requestBody.content?.schema; if (schema != null) { - if (schema.format == kBinary || schema.oneOf.isNotEmpty) { + if (schema.oneOf.length == 1) { + final oneOfRef = schema.oneOf.first.ref.getUnformattedRef(); + typeName = getValidatedClassName(oneOfRef); + } else 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, From 77f17cb13d1f28744e37c918cf32dc154921d16f Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 24 Jan 2024 14:30:14 +0300 Subject: [PATCH 84/93] Added override keyword to exceptionWords --- lib/src/exception_words.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/src/exception_words.dart b/lib/src/exception_words.dart index 26facfe1..bca978c6 100644 --- a/lib/src/exception_words.dart +++ b/lib/src/exception_words.dart @@ -55,5 +55,6 @@ List exceptionWords = [ 'try', 'client', 'hashCode', - 'value' + 'value', + 'override', ]; From b61b61320e5d0939532a7df0e31bed0ed2403d52 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Wed, 24 Jan 2024 17:30:00 +0300 Subject: [PATCH 85/93] Fixed generation of allOf models --- .../swagger_models_generator.dart | 29 +++++++++++++++++++ .../responses/swagger_schema.g.dart | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 25be4f2b..2e963a9b 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -145,6 +145,31 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { ); } + Map getAllOfProperties( + SwaggerSchema schema, + Map classes, + ) { + final properties = schema.properties; + for (var element in schema.allOf) { + properties.addAll(element.properties); + + if (element.ref.isNotEmpty) { + final neededClass = classes[element.ref.getUnformattedRef()]; + properties.addAll(neededClass?.properties ?? {}); + + if (neededClass != null) { + properties.addAll(getAllOfProperties(neededClass, classes)); + } + } else { + for (var allOf in element.allOf) { + properties.addAll(getAllOfProperties(allOf, classes)); + } + } + } + + return properties; + } + Map getClassesFromInnerClasses( Map classes, ) { @@ -156,6 +181,10 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { ...schema.items?.properties ?? {}, }; + final allOfProperties = getAllOfProperties(schema, classes); + + properties.addAll(allOfProperties); + for (var element in schema.allOf) { properties.addAll(element.properties); diff --git a/lib/src/swagger_models/responses/swagger_schema.g.dart b/lib/src/swagger_models/responses/swagger_schema.g.dart index 9ff3f5ea..25dfb5b1 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g.dart @@ -15,7 +15,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => (k, e) => MapEntry(k, SwaggerSchema.fromJson(e as Map)), ) ?? - const {}, + {}, items: json['items'] == null ? null : SwaggerSchema.fromJson(json['items'] as Map), From cb6dda871e48e39223da9a095265827403f308f8 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Mon, 29 Jan 2024 11:51:24 +0300 Subject: [PATCH 86/93] Revert "Fixed generation of allOf models" This reverts commit b61b61320e5d0939532a7df0e31bed0ed2403d52. --- .../swagger_models_generator.dart | 29 ------------------- .../responses/swagger_schema.g.dart | 2 +- 2 files changed, 1 insertion(+), 30 deletions(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 2e963a9b..25be4f2b 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -145,31 +145,6 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { ); } - Map getAllOfProperties( - SwaggerSchema schema, - Map classes, - ) { - final properties = schema.properties; - for (var element in schema.allOf) { - properties.addAll(element.properties); - - if (element.ref.isNotEmpty) { - final neededClass = classes[element.ref.getUnformattedRef()]; - properties.addAll(neededClass?.properties ?? {}); - - if (neededClass != null) { - properties.addAll(getAllOfProperties(neededClass, classes)); - } - } else { - for (var allOf in element.allOf) { - properties.addAll(getAllOfProperties(allOf, classes)); - } - } - } - - return properties; - } - Map getClassesFromInnerClasses( Map classes, ) { @@ -181,10 +156,6 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { ...schema.items?.properties ?? {}, }; - final allOfProperties = getAllOfProperties(schema, classes); - - properties.addAll(allOfProperties); - for (var element in schema.allOf) { properties.addAll(element.properties); diff --git a/lib/src/swagger_models/responses/swagger_schema.g.dart b/lib/src/swagger_models/responses/swagger_schema.g.dart index 25dfb5b1..9ff3f5ea 100644 --- a/lib/src/swagger_models/responses/swagger_schema.g.dart +++ b/lib/src/swagger_models/responses/swagger_schema.g.dart @@ -15,7 +15,7 @@ SwaggerSchema _$SwaggerSchemaFromJson(Map json) => (k, e) => MapEntry(k, SwaggerSchema.fromJson(e as Map)), ) ?? - {}, + const {}, items: json['items'] == null ? null : SwaggerSchema.fromJson(json['items'] as Map), From 15a1ee05e1716af4f3728873849a9214b23e4799 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Mon, 29 Jan 2024 12:00:46 +0300 Subject: [PATCH 87/93] Updated pubspec and changelog --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index ae65b130..843edf1c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.14.2 +version: 2.15.0 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 692fbdb0831d849dfb7b915d53593565231cee31 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Mon, 29 Jan 2024 12:05:22 +0300 Subject: [PATCH 88/93] Updated changelog --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index ae65b130..843edf1c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.14.2 +version: 2.15.0 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator From 324bd5c8f26bf50394f6a2a9bc1211acf7df22b6 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 5 Mar 2024 17:18:31 +0300 Subject: [PATCH 89/93] Fixed #722 generation of some files --- lib/src/code_generators/swagger_models_generator.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 25be4f2b..a812a778 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1646,7 +1646,8 @@ $allHashComponents; final newModelMap = allOf.firstWhereOrNull((m) => m.properties.isNotEmpty); - final currentProperties = schema.properties; + final currentProperties = + Map.from(schema.properties); currentProperties.addAll(newModelMap?.properties ?? {}); From 73708d367dfb96a0bad823f018a11c485475eb70 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 5 Mar 2024 17:28:00 +0300 Subject: [PATCH 90/93] Fixed generation of quoted in enum names --- lib/src/code_generators/enum_model.dart | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/src/code_generators/enum_model.dart b/lib/src/code_generators/enum_model.dart index d2674356..03f4689e 100644 --- a/lib/src/code_generators/enum_model.dart +++ b/lib/src/code_generators/enum_model.dart @@ -20,6 +20,10 @@ class EnumModel { @override String toString() => _getEnumContent(); + static String _normalizeJsonKeyString(String jsonKey) { + return jsonKey.replaceAll("\$", "\\\$").replaceAll('\'', '\\\''); + } + String _getEnumContent() { final resultStrings = []; @@ -42,10 +46,10 @@ class EnumModel { if (isInteger) { resultStrings.add( - "\t@JsonValue(${value.replaceAll("\$", "\\\$")})\n\t$validatedValue"); + "\t@JsonValue(${_normalizeJsonKeyString(value)})\n\t$validatedValue"); } else { resultStrings.add( - "\t@JsonValue('${value.replaceAll("\$", "\\\$")}')\n\t$validatedValue"); + "\t@JsonValue('${_normalizeJsonKeyString(value)}')\n\t$validatedValue"); } } @@ -97,7 +101,7 @@ const $name(this.value); result = '\$$result'; } - return '$result(${isInteger ? fieldValue : '\'$fieldValue\''})'; + return '$result(${isInteger ? fieldValue : '\'${_normalizeJsonKeyString(fieldValue)}\''})'; } String generateFromJsonToJson([bool caseSensitive = true]) { From 10aa6de88da81e98585a132e9d2ad91da6ebcaa4 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 5 Mar 2024 17:31:54 +0300 Subject: [PATCH 91/93] Fixed generation of some requests with enums --- 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 7139513b..ef5eeb79 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -636,7 +636,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return getValidatedClassName(neededKey).asEnum(); } - if (parameter.type == kArray) { + if (parameter.type == kArray || parameter.schema?.type == kArray) { final result = _getEnumParameterTypeName( parameterName: parameter.name, path: path, From 82fa1103421df75f0681d1192a74b3d623a255a5 Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 5 Mar 2024 17:45:13 +0300 Subject: [PATCH 92/93] 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 ef94c85f..5e0f5613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.15.1 + +* Fixed some issues + # 2.15.0 * Changed option `enums_case_sensitive` to correctly default to `true` as stated in documentation diff --git a/pubspec.yaml b/pubspec.yaml index 843edf1c..361e61d8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.15.0 +version: 2.15.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 ef1fc60095bc45817616f8d0005cd10e2975121a Mon Sep 17 00:00:00 2001 From: Uladzimir Paliukhovich Date: Tue, 5 Mar 2024 18:07:04 +0300 Subject: [PATCH 93/93] Fixed generation of some swaggers --- lib/src/code_generators/swagger_enums_generator.dart | 4 ++-- lib/src/code_generators/swagger_models_generator.dart | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index cc7fe650..7156fd92 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -353,9 +353,9 @@ ${allEnums.map((e) => e.toString()).join('\n')} ); if (propertiesContainer != null) { - properties = propertiesContainer.properties; + properties = Map.from(propertiesContainer.properties); } else { - properties = schema.properties; + properties = Map.from(schema.properties); } var allOfRef = allOf.firstWhereOrNull((e) => e.hasRef); diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index a812a778..0657f696 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -1656,7 +1656,7 @@ $allHashComponents; final allOfSchema = allClasses[allOf.ref.getUnformattedRef()]; if (allOfSchema != null) { - final properties = allOfSchema.properties; + final properties = Map.from(allOfSchema.properties); for (final allOf in allOfSchema.allOf) { properties.addAll(allOf.properties); }