schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
135 stars 20 forks source link

MappableField with key as raw String #207

Open outrelouxhe opened 1 week ago

outrelouxhe commented 1 week ago

I need to use a raw string for one key because one of the API I'm using (appwrite) is storing the id of a record in the '$id' field. However, the generated file does not take into account the 'r' before the string and it creates an error and I need to update manually the generated file. I have also tried to escape the $ by adding a \ in front of it but id doesn't not work.

Am I missing something or is there a workaround ? Thank you

@MappableClass()
class TranslatorModel extends TranslatorEntity with TranslatorModelMappable {
  /// Constructs a [TranslatorModel] instance.
  TranslatorModel({
    @MappableField(key: r'$id') required super.id,
    required super.surname,
    required super.firstname,
    required super.languages,
  });
}

From TranslatorModelMapper :

static const Field<TranslatorModel, String> _f$id =
      Field('id', _$id, key: '$id');
outrelouxhe commented 6 days ago

For information, I have implemented the following workaround using a hook on the MappableClass:

class TranslatorMappingHook extends MappingHook {
  const TranslatorMappingHook();
  @override
  Object? beforeDecode(Object? value) {
    if (value is Map<String, dynamic>) {
      // Set 'id' key with r'$id' value
      if (value.containsKey(r'$id')) {
        value['id'] = value[r'$id'];
      }
    }
    return value;
  }
}
schultek commented 4 days ago

Oh yes seems like a bug, will take a look