TypeScript AutoMapper

Tram Ho

AutoMapper

  • Hello, after using a library AutoMapper authored by Chau Tran . I would like to share the use-case that I apply in my backend project. In my projects, using the typeorm library to do orm helps me to persistent data implementation into the database, so I need to create quite a lot of entities (each entity will represent a table under the database). Now let’s see how we use AutoMapper.
  • Suppose you have an entity as follows:

  • In case you want to retrieve information of a user you will do the following:
    • let userInfo = userRepo.findOne(id);
    • Then return userInfo to the frontend. But there seems to be something wrong here. How can I return the user’s password to the frontend? So what’s the solution. Have a look at the title of the article, AutoMapper . Here I will guide you to use the basic features of this library.
  • Create a UserVm class as follows:

  • The rest is quite simple. Everything is left to AutoMapper lo =)). You only need to do two things as follows:
    • Mapper.createMap(User, UserVm);
    • let userInfo = Mapper.map(userRepo.findOne(id), UserVm);
  • After executing this command, the results returned to the frontend only exist with id and userName.
  • As you can see, using the library to implement a two-object mapper is quite simple. However, how to make the code cleaner, it will take more paper and ink. I would like to introduce to you in the following article. If you find it useful, remember the star for this library. Thank you for reading through the end of my article.
P / S: share more for ace friends near and far known that the author of this library is also very enthusiastic support. In the process of using if there is anything not understood or what issue the author can support people with video call =))
Share the news now

Source : Viblo