TypeScript Automapper
Inspired by MaDEiN83 mapper
Installation
$ npm install ts-mapper
Usage
Create map
To create a mapping between two objects, you must call the object method createMap
of the TypeMapper class.
It takes two interfaces:
- first interface must be the source interface
- second interface must be the destination interface
So, if we have an object of type ISource
and we want a object of type IDestination
, we should create a new mapping like that:
;; ;
Map fields
After we create a mapping between interfaces, we can now create all mappings between all wanted properties of our objects (source & destination).
For example, if we want to map the property sourceObject.srcOther
to destinationObjet.other
, we can define rule like that:
mapper.createMap; .mapsrc.srcProperty, dest.destProperty .mapsrc.srcOther, dest.other;
src
type isISource
dest
type isIDestination
You can chain your rules !
Conditionnal mapping
conditions
method allows you to check if the previous map
will be analysed and mapped to the destination object.
Example:
We want to map the property srcProperty
(source object) into destProperty
(destination object) only if the property visible
of the source object is true
.
mapper.createMap; .mapsrc.srcProperty, dest.destProperty .conditionss.visible;
The conditions
method takes two arguments:
- the source object
- the destination object
Examples:
mapper .createMap .mapsrc.my_prop, dest.myProp .conditionss.visible; mapper .createMap .mapsrc.my_prop, dest.myProp .conditionss.visible !== d.visible;
Fly and Casts
Sometime the source properties don't match the destination properties.
Example: sourceObject.age
can be a string
and destinationObject.age
is a number
.
To work with, you can cast property by chaining the is
method after a map
.
; mapper .createMap .mapp.age, p.age .isAutoMapperTypes.NUMBER;
Execution and Mapping
mapper .createMap .mapp.name, p.name .isAutoMapperTypes.STRING; ; ; mapper.mapsource, destination; console.logdestination;// {// name: "Marluan";// }