Skip to content

Advanced: profiles

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

Advanced topic: Profiles

By default, mappings are global. Also, there is only one mapping for each source and destination. In advanced cases, you could have a need to differentiate mapping configuration even further than just creating mappings. One of those cases is a differentiation in naming conventions between source and destination objects (e.g. PascalCase to camelCase property names). In those cases you mapping profiles are to the rescue. In order to make a mapping profile available for mapping, you have to instantiate the mapping profile and add it using the addProfile function. Profiles provide use with the possibility to use scoped mappings and mapping behaviors (like support for custom naming conventions).

Using Profiles

Using a profile is pretty straightforward. Profiles can be specified on initialization or when creating a mapping configuration for a certain source and destination.

Adding profiles on initialize

Profiles have to be configured during initalization using the configuration function's addProfile function:

class CamelCaseToPascalCaseMappingProfile extends AutoMapperJs.Profile {
    public sourceMemberNamingConvention: AutoMapperJs.INamingConvention;
    public destinationMemberNamingConvention: AutoMapperJs.INamingConvention;

    public profileName = 'CamelCaseToPascalCase';
    
    public configure() {
        this.sourceMemberNamingConvention = new AutoMapperJs.CamelCaseNamingConvention();
        this.destinationMemberNamingConvention = new AutoMapperJs.PascalCaseNamingConvention();
    }
}

automapper.initialize((config: AutoMapperJs.IConfiguration) => {
    config.addProfile(new CamelCaseToPascalCaseMappingProfile());
});

Specifying a profile to be used on mapping configuration

Specifying a mapping profile at initialization results in a profile being available, however, it will not be used yet. In order to use the defined profile, you should specify your profile on mapping configuration:

const sourceObject = { fullName: 'John Doe' };

automapper
    .createMap(sourceKey, destinationKey)
    .withProfile('CamelCaseToPascalCase');

var result = automapper.map(sourceKey, destinationKey, sourceObject);

expect(result).toEqualData({ FullName: 'John Doe' });