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

Conditionally preserve values from the destination object #547

Open
sbogeFS opened this issue May 22, 2023 · 1 comment
Open

Conditionally preserve values from the destination object #547

sbogeFS opened this issue May 22, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@sbogeFS
Copy link

sbogeFS commented May 22, 2023

Is your feature request related to a problem? Please describe.

I wanted to preserve values in the destination object if the value is undefined or null in the source object of the mapping for instance by updating a value.

Describe the solution you'd like

I wonder if it would be possible to have something like that:

createMap(mapper, SpecialOrderDto, CommonOrder,
      forMember(
        (destination) => destination.id,
        mapFrom((destination, source) => source.id ?? destination.id)),
      )
)

Describe alternatives you've considered

Currently I have to implement this logic without automapper.

Additional context

After posting this issue I wonder if mapWithArguments could be the correct way to handle this problem?

@sbogeFS sbogeFS added the enhancement New feature or request label May 22, 2023
@alfmoh
Copy link

alfmoh commented Jun 3, 2024

I had a similar problem. The way I solved it is by using the afterMap function:

createMap(
        mapper,
        UserDto,
        UserModel,
        forMember(
          (dest) => dest.phone,
          mapFrom((source) => {
            if (source.phone) {
              return source.phone.replace(/[- )(]/g, "");
            }
          })
        ),
        afterMap(removeUndefined())
      );

function removeUndefined() {
  return (_source, dest) => {
    const destObjKeys = Object.keys(dest);
    if (destObjKeys.length) {
      destObjKeys.forEach((key) => {
        if (dest[key] === undefined) {
          delete dest[key];
        }
      });
    }
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants