generateEnum method
Implementation
String generateEnum(
String enumName,
Iterable<Field> fields,
) {
final result = StringBuffer();
final enumFields = fields.whereType<EnumField>();
final supportedValues = enumFields.map((it) {
if (it.valueType.displayName == 'String') {
return '\\\'${it.value}\\\'';
} else {
return it.value;
}
}).join(',');
result.writeln('abstract class \$SerdesJson_${enumName}TypeAdapter {');
if (shouldGenerateFromJson) {
result.writeln(' static $enumName fromJson(String fieldName, dynamic json) {');
result.writeln(' final value = fromJsonNullable(fieldName, json);');
result.writeln(' if (value == null) {');
result.writeln(
' throw SchemeConsistencyException(\'field: "\$fieldName" can\\\'t be null\');',
);
result.writeln(' } else {');
result.writeln(' return value;');
result.writeln(' }');
result.writeln(' }');
result.writeln();
///
result.writeln(' static $enumName? fromJsonNullable(String fieldName, dynamic json) {');
result.writeln(' if (json == null || json == \'\') {');
result.writeln(' return null;');
result.writeln(' }');
result.write(' ');
for (final field in enumFields) {
if (field.valueType.displayName == 'String') {
result.writeln('if (json == \'${field.value}\') {');
} else {
result.writeln('if (json == ${field.value}) {');
}
result.writeln(' return $enumName.${field.name};');
result.write(' } else ');
}
result.writeln('{');
result.writeln(
' throw SchemeConsistencyException(\'Unsupported "$enumName" value: \$json for field "\$fieldName". Supported values: $supportedValues\');',
);
result.writeln(' }');
result.writeln(' }');
if (shouldGenerateToJson) {
result.writeln();
}
}
if (shouldGenerateToJson) {
result.writeln(' static dynamic toJson(String fieldName, $enumName object) {');
result.writeln(' final value = toJsonNullable(object);');
result.writeln(' if (value == null) {');
result.writeln(
' throw SchemeConsistencyException(\'field: "\$fieldName" can\\\'t be null\');',
);
result.writeln(' } else {');
result.writeln(' return value;');
result.writeln(' }');
result.writeln(' }');
result.writeln();
///
result.writeln(' static dynamic toJsonNullable($enumName? object) {');
result.writeln(' if (object == null) {');
result.writeln(' return null;');
result.writeln(' }');
result.writeln(' switch (object) {');
for (final field in fields.whereType<EnumField>()) {
result.writeln(' case $enumName.${field.name}:');
if (field.valueType.displayName == 'String') {
result.writeln(' return \'${field.value}\';');
} else {
result.writeln(' return ${field.value};');
}
}
result.writeln(' }');
result.writeln(' }');
}
result.writeln('}');
return result.toString();
}