generateUnions method
Implementation
String generateUnions(Iterable<Field> fields) {
final result = StringBuffer();
final unionFields = fields.whereType<UnionField>();
for (final field in unionFields) {
result.writeln();
final targetFields = fields.where((it) => it.jsonName == field.union);
if (targetFields.isEmpty) {
throw StateError(
'Couldn\'t find union field in shceme "${field.union}" for "${field.jsonName}" field');
}
final targetField = targetFields.first;
result.writeln(
' static ${field.type.displayName} _\$createUnion\$${field.name}(Map<String, dynamic> json) {',
);
result.writeln(
' final union = ' +
_jsonGetter(targetField.type, targetField.jsonName, 'json') +
'.toString();',
);
final contentType = field.type.isOptional
? parseType('Map<String, dynamic>?')
: parseType('Map<String, dynamic>');
result
.writeln(' final content = ' + _jsonGetter(contentType, field.jsonName, 'json') + ';');
result.writeln();
result.write(' ');
for (final value in field.unionValues) {
result.writeln('if (union == \'${value.value}\') {');
if (contentType.isOptional) {
result.writeln(' return ${value.type.displayName}.fromJson(content ?? {});');
} else {
result.writeln(' return ${value.type.displayName}.fromJson(content);');
}
result.write(' } else ');
}
result.writeln('{');
if (field.type.isOptional) {
result.writeln(' return null;');
} else {
final supportedTypes = field.unionValues.map((it) => it.value).join(',');
result.writeln(
' throw SchemeConsistencyException(\'Unsupported "${field.union}" value: \$union. Supported values: $supportedTypes\');',
);
}
result.writeln(' }');
result.writeln(' }');
}
return result.toString();
}