0
votes

I'm refactoring a web app to ensure that my entities are always initialized in a valid state. This means that I'm using DTOs for user input, and map those DTOs to my entities after validation.

However, some of the properties of the DTOs are not directly mappable to the properties of the entities. If a DTO contains a base64 encoded image and the entity requires a URL to the image file, I need to save the base64 to a file in the mapper in order to assign the URL of that file to the entity.

It could just be me, but it feels like this kind of stuff doesn't belong inside a DTO to entity mapper. Are there reasons why this might be a bad idea? What strategies are commonly used for this kind of mapping?

1
Could you post some example code of how you are doing this today? This will give us a better idea of how to properly advise you. - bman7716

1 Answers

1
votes

Seems to me that in your case you don't have a simple mapping process from DTOs to Entities because you have application logic in the process. Storing images somewhere and getting an URL/Path for that image is application specific logic, so you probably need a Service for it.

Applications usually have some kind of tasks or operations that it needs to perform and define the flow of the application. One way to define this flow is by using Commands and attach the DTO's to these Commands.

For example let's say you have a registration process so the user must enter some data and you need to create an Account Entity.

In case of web app, the frontend will have to collect user information and create and send a command to the backend. In this case you will have RegisterUserCommand. This command will contain a UserInfo DTO property, or will have properties for the user info. For example:

RegisterUserCommand {

   string UserName
   string FirstName;
   string LastName;
   Image Avatar;
}

The next thing you need is a RegisterUserCommandService or (RegisterUserCommandHandler depending on your taste and terminology used) that will process/handle the Command. You also need a StorageProvider that will provider service operations for storing and retrieving images (can be on the File System, Amazon S3, Dropbox etc.) and give you a link. Here is a sample pseudo code

RegisterUserCommandService {

  Process(RegisterUserCommand cmd) {

     avatarLink = storageProvider.Store(cmd.Avatar);

     account = new Account(cmd.UserName, ...., avatarLink);

     accountRepository.Save(account);
}

If you tell me more about your application I can provider an example for your specific case.

Here are some resources you can check: