Skip to content

Reusing existing mapper to avoid code duplication #92

Description

@andreadelfante

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;
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions