schultek / stormberry

Access your postgres database effortlessly from dart code.
https://pub.dev/packages/stormberry
MIT License
68 stars 17 forks source link

Type conversion fails for List<CustomModels> with nullable parameters #60

Open DamienLeon opened 1 year ago

DamienLeon commented 1 year ago

Hi, I have an AddressModel class with fromJson expecting a type of Map<String, dynamic> as few parameters are nullable. I store List<AddressModel> in another model and I have the TypeConverter for AddressModel as follows:

class AddressConverter extends TypeConverter<Address> {
  const AddressConverter() : super('jsonb');

  @override
  Map<String, dynamic> encode(Address value) => value.toJson();

  @override
  Address decode(dynamic value) {
    if (value is Map<String, dynamic>) {
      return Address.fromJson(value);
    } else {
      log(value.toString(), name: "Address Parsing Error");
      throw Exception("Parsing error: Unable to parse");
    }
  }
}

Now, the issue is that when the type conversion happens, it expects a List<Object> but finds a List<dynamic>. The workaround is to manually change List<Object> to List<dynamic> in the PostgresBinaryEncoder().convert() function from the postgres package as follows:

case PgDataType.jsonbArray:
        {
          if (input is List<dynamic>)  // Here, List<Object> is changed to List<dynamic>
          {
            final objectsArray = input.map((v) => utf8.encode(json.encode(v)));
            return writeListBytes<List<int>>(objectsArray, 3802, (item) => item.length + 1,
                (writer, item) {
              writer.writeUint8(1);
              writer.write(item);
            });
          }
          throw FormatException(
              'Invalid type for parameter value. Expected: List<Object> Got: ${input.runtimeType}');
        }

The code runs fine after his change and the data entry is added to the database. I am not sure if any changes can be made in AddressConverter code to resolve this issue.

Flutter 3.7.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 62bd79521d (13 days ago) • 2023-03-30 10:59:36 -0700
Engine • revision ec975089ac
Tools • Dart 2.19.6 • DevTools 2.20.1

stormberry: ^0.13.0
schultek commented 1 year ago

Sounds like an issue with the postgres package. At least I don't have another idea right now so maybe just open a PR there to apply the fix with List<dynamic>