Carapacik / swagger_parser

Dart package that takes an OpenApi definition file and generates REST clients based on retrofit and data classes for your project.
https://pub.dev/packages/swagger_parser
MIT License
87 stars 33 forks source link

fix: Handle Empty Enum Value Case #238

Closed Sadhorsephile closed 1 month ago

Sadhorsephile commented 1 month ago

Problem

If we have a such enum:

    BlankEnum:
      enum:
      - ''

we'll get this:

// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:json_annotation/json_annotation.dart';

@JsonEnum()
enum BlankEnum {
  @JsonValue()
  (),
  /// Default value for all unparsed values, allows backward compatibility when adding new values on the backend.
  $unknown(null);

  const BlankEnum(this.json);

  factory BlankEnum.fromJson(dynamic json) => values.firstWhere(
        (e) => e.json == json,
        orElse: () => $unknown,
      );

  final dynamic? json;
}

Solution

If value of enum is empty string, we just use empty as its name:

// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, unused_import

import 'package:json_annotation/json_annotation.dart';

@JsonEnum()
enum BlankEnum {
  @JsonValue('')
  empty(''),
  /// Default value for all unparsed values, allows backward compatibility when adding new values on the backend.
  $unknown(null);

  const BlankEnum(this.json);

  factory BlankEnum.fromJson(dynamic json) => values.firstWhere(
        (e) => e.json == json,
        orElse: () => $unknown,
      );

  final dynamic? json;
}
StarProxima commented 1 month ago

Thank you for your contribution. LGTM