Overview
What is AutoMapper?
AutoMapper (TypeScript) is an object-object mapper by convention. When two objects' models are conventionally matching, AutoMapper can map the two objects with almost zero mapping configuration.
Why use AutoMapper?
Writing code for mapping (especially when they are conventionally matching) is boring; writing tests for these mappings is even more boring. With AutoMapper, you can automate these tasks and separate the logic of transforming one Object Type to another.
However, AutoMapper is an opinionated tool. While mapping configuration is an essential API of AutoMapper that provides customizations, you are probably better off not using AutoMapper if you find your mappings are mostly manual mapping configurations.
Jimmy Bogard, the author of .NET AutoMapper, writes a blog post to express his design philosophy when he worked on .NET AutoMapper. The summary is below
AutoMapper works because it enforces a convention. It assumes that your destination types are a subset of the source type. It assumes that everything on your destination type is meant to be mapped. It assumes that the destination member names follow the exact name of the source type. It assumes that you want to flatten complex models into simple ones.
All of these assumptions come from our original use case - view models for MVC, where all of those assumptions are in line with our view model design. With AutoMapper, we could enforce our view model design philosophy. This is the true power of conventions - laying down a set of enforceable design rules that help you streamline development along the way.
By enforcing conventions, we let our developers focus on the value add activities, and less on the activities that provided zero or negative value, like designing bespoke view models or writing a thousand dumb unit tests.
And this is why our usage of AutoMapper has stayed so steady over the years - because our design philosophy for view models hasn't changed. If you find yourself hating a tool, it's important to ask - for what problems was this tool designed to solve? And if those problems are different than yours, perhaps that tool isn't a good fit.
Ecosystem
AutoMapper comes with a core
library and many strategies that allow you to work with different use-case in your JS/TS projects.
Core
As the name suggests, @automapper/core
deals with tracking models' metadata, setting up mapping configurations, storing Mappings, and executing the mapping operations between the models.
Strategies
Strategy | Description |
---|---|
@automapper/classes | Works with TS/ES6 Class |
@automapper/pojos | Works with plain objects and Interface |
@automapper/mikro | Works with TS/ES6 Class and MikroORM |
@automapper/sequelize | Works with TS/ES6 Class and Sequelize |
NestJS
AutoMapper has an official integration with NestJS framework with the @automapper/nestjs
package.