-
Notifications
You must be signed in to change notification settings - Fork 36
advanced: type converters
Standard mapping is very useful in many situations. However, there are some scenarios in which mapping will not provide the expected result. That is where custom type converters come to play.
The createMap.convertUsing function specifies a custom type converter to be used when mapping a source to a destination. Using this function means skipping normal member mapping and converting using a custom type converter. This type converter will be instantiated (when using a class) or executed (when using a function) during mapping.
The actual function used (whether using a class or a function) has to specify one resolutionContext
parameter of interface type AutoMapperJs.IResolutionContext
. Failing this condition will cause mapping to fail.
var objA = { propA: 'propA' };
var fromKey = '{D1534A0F-6120-475E-B7E2-BF2489C58571}';
var toKey = '{1896FF99-1A28-4FE6-800B-072D5616B02D}';
automapper
.createMap(fromKey, toKey)
.convertUsing(function (resolutionContext : AutoMapperJs.IResolutionContext) {
return { propA: resolutionContext.sourceValue.propA + ' (custom mapped with resolution context)' }
});
// act
var objB = automapper.map(fromKey, toKey, objA);
// assert
expect(objB.propA).toEqual(objA.propA + ' (custom mapped with resolution context)');
Class definition sample:
class CustomTypeConverter extends AutoMapperJs.TypeConverter {
public convert(resolutionContext: AutoMapperJs.IResolutionContext): any {
return { propA: resolutionContext.sourceValue.propA + ' (convertUsing with a class definition)' };
}
}
Usage:
// arrange
var objA = { propA: 'propA' };
var fromKey = '{6E7F5757-1E55-4B55-BB86-44FF5B33DE2F}';
var toKey = '{8521AE41-C3AF-4FCD-B7C7-A915C037D69E}';
automapper
.createMap(fromKey, toKey)
.convertUsing(CustomTypeConverter);
// act
var objB = automapper.map(fromKey, toKey, objA);
// assert
expect(objB.propA).toEqual(objA.propA + ' (convertUsing with a class definition)');
AutoMapperTS is Copyright © 2015 Bert Loedeman and other contributors under the MIT license.
Getting started
Mapping performance
Initialization (initialize)
Mapping configuration (createMap)
- forMember
- forSourceMember
- condition
- forAllMembers
- ignoreAllNonExisting
- convertToType
- convertUsing
- withProfile
Validation (assertConfigurationIsValid)
Mapping (map)
Currying
Custom type converters
Profiles
Chaining
Naming conventions
Asynchronous mapping
Flattening and nesting