Skip to content

Custom MapType #146

Description

@DevNico

I have the use case that I need to define a custom mapping function for an entire object. The problem is that this Object has inner objects which can be "automatically" mapped by other MapType definitions.

My proposed solution would be to dynamically inject an instance of the mapper into the custom convert function. This could be done for both a new MapType.custom but also the existing custom conversion functions in TypeConverters and Field.customs. The idea would be to "detect" that the provided function takes in two parameters instead of one e.g. when looking at Field.custom not only accepting Target Function(Source dto) but also Target Function(MapprInstance mappr, Source dto).

A full example of this imaginary syntax could look like this:

class WrapperDto {
  final SuperStringDto? superStringDto;
  final SuperIntDto? superIntDto;
}

sealed class Wrapper {}
class StringWrapper implements Wrapper {
  final SuperString superString;
}
class IntWrapper implements Wrapper {
  final SuperInt superInt;
}

class SuperStringDto {}
class SuperString {}

class SuperIntDto {}
class SuperInt {}

@AutoMappr([
  MapType<WrapperDto, Wrapper>.custom(mapWrapper),
  MapType<SuperStringDto, SuperString>(),
  MapType<SuperIntDto, SuperInt>(),
])
class ImaginaryMappr extends $ImaginaryWrapper {
  const ImaginaryMappr();
}

Wrapper mapWrapper(ImaginaryMappr mappr, WrapperDto dto) {
  if (dto.superStringDto != null) {
    return StringWrapper(mappr.convert(dto.superStringDto!));
  }

  if (dto.superIntDto != null) {
    return IntWrapper(mappr.convert(dto.superIntDto!));
  }

  throw Exception('Invalid wrapper dto');
}

I'd be open to implement this feature because unless I overlooked some existing feature to handle my use case I am kinda dependent on a solution :D

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions