Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: #290 supports oneOf polymorphic types with dart_mappable #292

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,28 @@ String dartDartMappableDtoTemplate(
required bool markFileAsGenerated,
}) {
final className = dataClass.name.toPascal;

final parent = dataClass.discriminatorValue?.parentClass;

return '''
${generatedFileComment(markFileAsGenerated: markFileAsGenerated)}
${dartImportDtoTemplate(JsonSerializer.dartMappable)}
${dartImports(imports: dataClass.imports)}
part '${dataClass.name.toSnake}.mapper.dart';

${descriptionComment(dataClass.description)}@MappableClass()
class $className with ${className}Mappable {
${descriptionComment(dataClass.description)}@MappableClass(${() {
if (dataClass.discriminator != null) {
return [
"discriminatorKey: '${dataClass.discriminator!.propertyName}'",
"includeSubClasses: [${dataClass.discriminator!.discriminatorValueToRefMapping.keys.join(', ')}]",
].join(", ");
}
if (dataClass.discriminatorValue != null) {
return "discriminatorValue: '${dataClass.discriminatorValue!.propertyValue}'";
}
return "";
}()})
class $className ${parent != null ? "extends $parent " : ""}with ${className}Mappable {

${indentation(2)}const $className(${getParameters(dataClass)});

Expand All @@ -34,16 +48,26 @@ ${indentation(
}

String getParameters(UniversalComponentClass dataClass) {
if (dataClass.parameters.isNotEmpty) {
return '{\n${_parametersToString(dataClass.parameters)}\n${indentation(2)}}';
// if this class has discriminated values, don't populate the discriminator field
// in the parent class
final parameters = dataClass.parameters
.where((it) => it.name != dataClass.discriminator?.propertyName)
.toList();
if (parameters.isNotEmpty) {
return '{\n${_parametersToString(parameters)}\n${indentation(2)}}';
} else {
return '';
}
}

String getFields(UniversalComponentClass dataClass) {
if (dataClass.parameters.isNotEmpty) {
return '${_fieldsToString(dataClass.parameters)}\n';
// if this class has discriminated values, don't populate the discriminator field
// in the parent class
final parameters = dataClass.parameters
.where((it) => it.name != dataClass.discriminator?.propertyName)
.toList();
if (parameters.isNotEmpty) {
return '${_fieldsToString(parameters)}\n';
} else {
return '';
}
Expand Down
14 changes: 12 additions & 2 deletions swagger_parser/lib/src/parser/model/universal_component_class.dart
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
part of 'universal_data_class.dart';

/// Universal template for containing information about component
@immutable
final class UniversalComponentClass extends UniversalDataClass {
/// Constructor for [UniversalComponentClass]
const UniversalComponentClass({
UniversalComponentClass({
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to remove the const constuctor as the discriminatorValue field needs to be updated after the initial UniversalComponentClass class is constructed.

required super.name,
required this.imports,
required this.parameters,
this.allOf,
this.typeDef = false,
this.discriminator,
this.discriminatorValue,
super.description,
});

/// List of additional references to components
final Set<String> imports;

/// The import of this class
String get import => name.toPascal;

/// List of class fields
final List<UniversalType> parameters;

Expand All @@ -35,6 +38,13 @@ final class UniversalComponentClass extends UniversalDataClass {
Map<String, List<UniversalType>> refProperties,
})? discriminator;

/// When using a discriminated oneOf, where this class is one of the discriminated values, this field contains the information about the parent
({
// The name of the property that is used to discriminate the oneOf variants
String propertyValue,
String parentClass,
})? discriminatorValue;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This discriminatorValue field could potentially be combined with discriminator above, perhaps adding an extra field to denote whether this class is a discrinator parent or discriminated value class.


/// Whether or not this schema is a basic type
/// "Date": {
/// "type": "string",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:collection/collection.dart';
import 'package:meta/meta.dart';

import '../utils/case_utils.dart';
import '../utils/type_utils.dart';
import 'universal_type.dart';

Expand Down
7 changes: 7 additions & 0 deletions swagger_parser/lib/src/parser/parser/open_api_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,13 @@ class OpenApiParser {
}
discriminator.refProperties[ref] = refedClass.parameters;
discriminatedOneOfClass.imports.addAll(refedClass.imports);
discriminatedOneOfClass.imports.add(refedClass.import);

refedClass.imports.add(discriminatedOneOfClass.import);
refedClass.discriminatorValue = (
propertyValue: ref,
parentClass: discriminatedOneOfClass.name,
);
}
}

Expand Down
13 changes: 13 additions & 0 deletions swagger_parser/test/e2e/e2e_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,19 @@ void main() {
);
});

test('discriminated_one_of.3.0_mappable', () async {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to combine this test with the discriminated_one_of.3.0 test above.

I've opened #291 to suggest some changes to the test structure to allow this.

await e2eTest(
'basic/discriminated_one_of.3.0_mappable',
(outputDirectory, schemaPath) => SWPConfig(
outputDirectory: outputDirectory,
schemaPath: schemaPath,
jsonSerializer: JsonSerializer.dartMappable,
putClientsInFolder: true,
),
schemaFileName: 'discriminated_one_of.3.0.json',
);
});

test('empty_class.2.0', () async {
await e2eTest(
'basic/empty_class.2.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import 'package:freezed_annotation/freezed_annotation.dart';

import 'cat_type.dart';
import 'family_members_union.dart';

part 'cat.freezed.dart';
part 'cat.g.dart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import 'package:freezed_annotation/freezed_annotation.dart';

import 'dog_type.dart';
import 'family_members_union.dart';

part 'dog.freezed.dart';
part 'dog.g.dart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

import 'package:freezed_annotation/freezed_annotation.dart';

import 'cat.dart';
import 'cat_type.dart';
import 'dog.dart';
import 'dog_type.dart';
import 'human.dart';
import 'human_type.dart';

part 'family_members_union.freezed.dart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'package:freezed_annotation/freezed_annotation.dart';

import 'family_members_union.dart';
import 'human_type.dart';

part 'human.freezed.dart';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"openapi": "3.1.0",
"info": {
"title": "Family API",
"version": "1.0.0"
},
"paths": {},
"components": {
"schemas": {
"Family": {
"type": "object",
"properties": {
"members": {
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#/components/schemas/Cat"
},
{
"$ref": "#/components/schemas/Dog"
},
{
"$ref": "#/components/schemas/Human"
}
],
"discriminator": {
"propertyName": "type",
"mapping": {
"Cat": "#/components/schemas/Cat",
"Dog": "#/components/schemas/Dog",
"Human": "#/components/schemas/Human"
}
}
}
}
}
},
"Cat": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["Cat"]
},
"mewCount": {
"type": "integer",
"description": "Number of times the cat meows."
}
},
"required": ["type", "mewCount"]
},
"Dog": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["Dog"]
},
"barkSound": {
"type": "string",
"description": "The sound of the dog's bark."
}
},
"required": ["type", "barkSound"]
},
"Human": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["Human"]
},
"job": {
"type": "string",
"description": "The job of the human."
}
},
"required": ["type", "job"]
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

// Data classes
export 'models/family.dart';
export 'models/cat.dart';
export 'models/dog.dart';
export 'models/human.dart';
export 'models/family_members_union.dart';
export 'models/cat_type.dart';
export 'models/dog_type.dart';
export 'models/human_type.dart';
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:dart_mappable/dart_mappable.dart';

import 'cat_type.dart';
import 'family_members_union.dart';

part 'cat.mapper.dart';

@MappableClass(discriminatorValue: 'Cat')
class Cat extends FamilyMembersUnion with CatMappable {
const Cat({
required this.type,
required this.mewCount,
});

final CatType type;
final int mewCount;

static Cat fromJson(Map<String, dynamic> json) =>
CatMapper.ensureInitialized().decodeMap<Cat>(json);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:dart_mappable/dart_mappable.dart';

part 'cat_type.mapper.dart';

@MappableEnum()
enum CatType {
@MappableValue('Cat')
cat,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:dart_mappable/dart_mappable.dart';

import 'dog_type.dart';
import 'family_members_union.dart';

part 'dog.mapper.dart';

@MappableClass(discriminatorValue: 'Dog')
class Dog extends FamilyMembersUnion with DogMappable {
const Dog({
required this.type,
required this.barkSound,
});

final DogType type;
final String barkSound;

static Dog fromJson(Map<String, dynamic> json) =>
DogMapper.ensureInitialized().decodeMap<Dog>(json);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:dart_mappable/dart_mappable.dart';

part 'dog_type.mapper.dart';

@MappableEnum()
enum DogType {
@MappableValue('Dog')
dog,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:dart_mappable/dart_mappable.dart';

import 'family_members_union.dart';

part 'family.mapper.dart';

@MappableClass()
class Family with FamilyMappable {
const Family({
required this.members,
});

final List<FamilyMembersUnion> members;

static Family fromJson(Map<String, dynamic> json) =>
FamilyMapper.ensureInitialized().decodeMap<Family>(json);
}
Loading