mapper icon indicating copy to clipboard operation
mapper copied to clipboard

Conditionally preserve values from the destination object

Open sbogeFS opened this issue 2 years ago • 1 comments

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 avatar May 22 '23 10:05 sbogeFS

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

alfmoh avatar Jun 03 '24 11:06 alfmoh