Skip to content

create map convert to type

Bert Loedeman edited this page Sep 11, 2015 · 2 revisions

convertToType

By default, the Arcady AutoMapper implementation creates an empty object literal when converting a source object to a destination. This somewhat looks like (pseudocode):

var a = { prop: 'Value' };
automapper.map((src: string, dst: string, srcObj: any) => {
  var dstObj = {};
  for (var prop in srcObj) {
    dstObj[prop] = srcObj[prop];
  }
});

The createMap.convertToType function specifies which destination object should be constructed (using the new() keyword) when mapping a certain source object to its destination counterpart. This makes it possible use inherited functions from base objects, verification if an object is an instance of a certain type (and even more sweetness, I assume). The functionality looks like (pseudocode):

var a = { prop: 'Value' };
automapper.map((src: string, dst: string, srcObj: any) => {
  // create empty destination object.
  var destinationObject = destinationTypeClass ? new destinationTypeClass() : {};
  // ...
});

Usage sample

The class definition:

class DemoToBusinessType {
}

Using the defined class:

//arrange
var objA = { ApiProperty: 'From A' };


var fromKey = '{7AC4134B-ECC1-464B-B144-5C9D8F5B5A7E}';
var toKey = '{2BDE907C-1CE6-4CC5-A601-9A94CA6C4737}';

automapper
	.createMap(fromKey, toKey)
	.forMember('property', (opts: AutoMapperJs.IMemberConfigurationOptions) => { opts.mapFrom('ApiProperty'); })
	.convertToType(DemoToBusinessType);

// act
var objB = automapper.map(fromKey, toKey, objA);

// assert
expect(objB instanceof DemoToBusinessType).toBeTruthy();
expect(objB.property).toEqual(objA.ApiProperty);
Clone this wiki locally