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

I have a question about reverseMap() function. #109

Closed
cesc1802 opened this issue Apr 27, 2020 · 2 comments
Closed

I have a question about reverseMap() function. #109

cesc1802 opened this issue Apr 27, 2020 · 2 comments

Comments

@cesc1802
Copy link

I create a profile by using function createMap(), and i need to convert some field has type Date to string. Now, I want to when i receive data from client using reverseMap() with convert again string to Date. Pls help me provide some example. Thanks

@nartc
Copy link
Owner

nartc commented Apr 27, 2020

class Foo {
   @AutoMap()
   date: Date;
}

class FooDto {
   @AutoMap()
   date: string;
}

When working with Date Time, it's quite tricky because AutoMapper cannot determine how you want to convert a Date to a string (https://automapper.netlify.app/docs/usages/features/date-time). When you have a conversion from Date <-> string, it's best to use mapFrom() to handle these cases.

Mapper.createMap(Foo, FooDto)
   .forMember(d => d.date, mapFrom(s => s.date.toDateString()))
   .reverseMap()
   .forPath(s => s.date, mapFrom(d => new Date(d.date)));

If you have a more complex use-case for this type of conversion, then I'd suggest to use a Converter (https://automapper.netlify.app/docs/usages/mapping-configuration/for-member/converter)

export class StringDateConverter extends Converter<string, Date> {
   convert(source: string): Date {
      // maybe run your validation on the date string
      return new Date(source);
   }
}

export class DateStringConverter extends Converter<Date, string> {
   convert(source: Date): string {
      return source.toDateString();
   }
}
Mapper.createMap(Foo, FooDto)
   .forMember(d => d.date, convertUsing(new DateStringConverter(), s => s.date))
   .reverseMap()
   .forPath(s => s.date, convertUsing(new StringDateConverter(), d => d.date));

Hopefully you find these information helpful!

@cesc1802
Copy link
Author

@nartc thanks for support as soon. i will completed follow your sample

@nartc nartc closed this as completed Apr 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants