gibahjoe / openapi-generator-dart

Openapi Generator for Dart/Flutter
BSD 3-Clause "New" or "Revised" License
112 stars 29 forks source link

deserialize Enum from {insert type here}. With partial solution(code snippet that can be inserted[needs to fill in filename, enum name, value type]) #147

Open singersbalm opened 1 month ago

singersbalm commented 1 month ago

Description of the bug

When the return type is a enum the deserializer is skipped. the body in the switch is empty. I implemented a fromValue for me. This shouldn't be that hard to generate. Maybe something like this would be easier.

everything within {} should be filled in by the code generator.

{filename}.dart

part '{filename}.g.dart';

@JsonEnum(alwaysCreate: true)

...

factory {enum}.fromValue({valueType} value) {
    if (_${enum}EnumMap.containsValue(value)) {
      return _${enum}EnumMap.entries
          .firstWhere((element) => element.value == value)
          .key;
    } else {
      throw ArgumentError('Invalid value for {enum} enum: $value');
    }
  }

deserialize.dart

case '{enum}':
          return {enum}.fromValue(value as  {valueType}) as ReturnType;

Steps to reproduce

  1. route with a enum as return type
  2. openapi-generator generate -i http://127.0.0.1:8080/openapi-docs.yml -g dart-dio -o api --additional-properties=serializationLibrary=json_serializable

Expected behavior

First attempt to fix the deserialize. Does the same as solution above

//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//

// ignore_for_file: unused_element
import 'package:json_annotation/json_annotation.dart';

enum Success {
      @JsonValue(r'True')
      true_(r'True'),
      @JsonValue(r'False')
      false_(r'False');

  const Success(this.value);

  factory Success.fromValue(String value) {
    switch (value) {
      case 'True':
        return Success.true_;
      case 'False':
        return Success.false_;
      default:
        throw ArgumentError('Invalid value for Success enum: $value');
    }
  }

  final String value;
  @override
  String toString() => value;
}
case 'Success':
          return Success.fromValue(value as String) as ReturnType;

Logs

No response

Screenshots

No response

Platform

Linux

Library version

latest

Flutter version

latest

Flutter channel

stable

Additional context

No response