Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reusing existing mapper to avoid code duplication #92

Open
andreadelfante opened this issue Dec 22, 2023 · 0 comments
Open

Reusing existing mapper to avoid code duplication #92

andreadelfante opened this issue Dec 22, 2023 · 0 comments

Comments

@andreadelfante
Copy link

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;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant