smartstruct icon indicating copy to clipboard operation
smartstruct copied to clipboard

Reusing existing mapper to avoid code duplication

Open andreadelfante opened this issue 1 year ago • 0 comments

Hi, this library looks great! What about implementing the uses feature in the @Mapper annotation?

https://mapstruct.org/documentation/dev/reference/html/#_advanced_mapping_options

Using this flag, developers can reduce the code duplication to map existing objects, by plugging other mappers into the parent one.

Example

Entities

// TARGET

class ParentTarget {
  ParentTarget(this.childTarget);

  final ChildTarget childTarget;
}

class ChildTarget {
  ChildTarget(this.property);

  final String property;
}

// SOURCE

class ParentSource {
  ParentSource(this.childSource);

  final ChildSource childSource;
}

class ChildSource {
  ChildSource(this.property);

  final String property;
}

Mappers

@Mapper()
abstract class ChildMapper {
  @Mapping(source: 'childSource', target: 'childTarget')
  ChildTarget toChildTarget(ChildSource model);
}

@Mapper(uses: [ChildMapper])
abstract class ParentMapper {
  ParentTarget toParentTarget(ParentSource model);
}

The generated code should be something like down below.

class ParentMapperImpl extends ParentMapper {
  final ChildMapper childMapper;

  ParentMapperImpl({
    required this.childMapper,
  }) : super();

  ParentTarget toParentTarget(ParentSource model) {
    final parentTarget = ParentTarget(childMapper.toChildTarget(model.childSource));
    return parentTarget;
  }
}

andreadelfante avatar Dec 22 '23 23:12 andreadelfante