handleEnumToStringConversion static method

ClassProperty handleEnumToStringConversion({
  1. required TypeNode fieldType,
  2. required TypeName dartTypeName,
  3. required ClassPropertyName name,
  4. required Map<String, String> jsonKeyAnnotation,
})

Handle enum-to-string conversion logic for class properties

Implementation

static ClassProperty handleEnumToStringConversion({
  required TypeNode fieldType,
  required TypeName dartTypeName,
  required ClassPropertyName name,
  required Map<String, String> jsonKeyAnnotation,
}) {
  if (fieldType is ListTypeNode) {
    // For lists of enums, we need to modify the type to be List<String>
    // Use a simpler approach to avoid json_serializable errors
    // Don't use complex lambda expressions in JsonKey annotations

    // Override the dartTypeName to be List<String>
    return ClassProperty(
      type: ListOfTypeName(
        typeName: TypeName(name: 'String'),
        isNonNull: dartTypeName.isNonNull,
      ),
      name: name,
      // No custom fromJson/toJson functions, let json_serializable handle it
      annotations: name.namePrintable != name.name
          ? ['JsonKey(name: \'${name.name}\')']
          : [],
    );
  } else {
    // For single enums, we'll return a String
    // Create the JSON key annotation string with consistent ordering
    final orderedEntries = <String>[];
    if (jsonKeyAnnotation.containsKey('name')) {
      orderedEntries.add('name: ${jsonKeyAnnotation['name']}');
    }
    if (jsonKeyAnnotation.containsKey('unknownEnumValue')) {
      orderedEntries.add(
        'unknownEnumValue: ${jsonKeyAnnotation['unknownEnumValue']}',
      );
    }
    // Add any other entries
    for (final entry in jsonKeyAnnotation.entries) {
      if (entry.key != 'name' && entry.key != 'unknownEnumValue') {
        orderedEntries.add('${entry.key}: ${entry.value}');
      }
    }
    final jsonKey = orderedEntries.join(', ');

    return ClassProperty(
      type: TypeName(name: 'String', isNonNull: dartTypeName.isNonNull),
      name: name,
      annotations: jsonKeyAnnotation.isEmpty ? [] : ['JsonKey($jsonKey)'],
    );
  }
}