Mapper Utility Examples

The Mapper class is a utility to map the properties from schemas in API namespaces to entity instances in domain namespaces and vice versa.

There are two default methods available in the Mapper class:
  • mapSchemaToEntity
  • mapEntityToSchema

Furthermore, it is possible to create custom methods.

Mapper Class

Mapper class extends BaseMapper class from solution-framework which provides access to
  • factory methods (such as entity, schema, external and reference)
  • instanceOf method
  • log method

Example of a Mapper class implementation:


/**
* This class can be used to implement mapping logic between schemas and entities,
* It has access to instanceOf operator, factory and logger.
*/
export class Mapper extends Mappers.BaseMapper {

    constructor(context: Context) {
        super(context);
    }

    public mapSchemaToEntity(schema: ObjectSchemaObject): Entity {
        const log = this.log;
        log.debug('mapSchemaToEntity()');

        // Extract schema object
        { personalCardNumber, personalCardName } = schema._getJSON();

        // Create entity instance
        const creditCard = this.factory.entity.cc.CreditCard();

        // Add mapping implementation
        creditCard.cardNumber = personalCardNumber;
        creditCard.cardText = personalCardName;

        return creditCard;
    }

    public mapEntityToSchema(entity: Entity): ObjectSchemaObject {
        const log = this.log;
        log.debug('mapEntityToSchema()');
        // Add mapping implementation

        return null;
    }

    // Add any other specific mapping methods
    public mapEntityToSchemaCustomMethod(entity: Entity): ObjectSchemaObject {
        const log = this.log;
        log.debug('mapEntityToSchemaCustomMethod()');
        // Add mapping implementation

        return null;
    }

    /**
    * This method is needed for logging purposes to provide file path to log statements.
    */
    protected getSrcImplPath(): string {
        return 'src-impl/util/Mapper';
    }

}
            

Example for using the Mapper class in an Operation class:


import { Mapper } from '../../../util/Mapper';

export default class extends operations.ccApi_createCreditCard {

    public async execute(): Promise<void> {
        const log = this.util.log;
        log.debug('ehns_getPizza.execute()');
        
        const Mapper1 = new Mapper(this.context);

        // Entity Instance
        const creditCardInput = Mapper1.mapSchemaToEntity(this.factory.schema.ccApi.CreateCreditCard());
        
        // Further implementation
    }
}