Model Mapper in Angular

Hi Friends, This is Lakshman here.

As part of the Series "Angular Best Practices".

Today, We will Model Mapper in Angular.

Pre-requisites:

The pre-requisites are

Model Mapper

It's a concept build based on AutoMapper from C#.

While integrating with API, When we were required to map property.

The Model Mapper requires Two things to do,

  • ModelMapper Class
  • PropertyMap Function.

The ModelMapper class file as below,

export class ModelMapper<T> {
  _propertyMapping: any;
  _target: any;
  constructor(type: { new(): T }) {
    this._target = new type();
    this._propertyMapping = this._target.constructor._propertyMap;
  }

  map(source: any) {
    Object.keys(this._target).forEach((key) => {
      const mappedKey = this._propertyMapping[key];
      if (mappedKey) {
        this._target[key] = source[mappedKey];
      } else {
        this._target[key] = source[key];
      }
    });
    Object.keys(source).forEach((key) => {
      const targetKeys = Object.keys(this._target);
      if (targetKeys.indexOf(key) === -1) {
        this._target[key] = source[key];
      }
    });
    return this._target;
  }
}

The PropertyMap Function as below,

export function propertyMap(sourceProperty: string) {
  return function (target: any, propertyKey: string) {
    if (!target.constructor._propertyMap) {
      target.constructor._propertyMap = {};
    }
    target.constructor._propertyMap[propertyKey] = sourceProperty;
  };
}

To Use

  • We are required to create the Class like below,
import { propertyMap } from "@core/mapper";

export interface IPostOffice {
    PostOffice: string;
    City: string;
    State: string;
}

export class PostOffice implements IPostOffice {
    @propertyMap('Name')
    PostOffice: string;
    @propertyMap('District')
    City: string;
    @propertyMap('State')
    State: string;

    constructor() {
        this.PostOffice = '';
        this.City = '';
        this.State = '';
    }
}
  • For Mapping as like below,
  ...
  SearchPostofficeByPinCode(pincode: string) {
    const url = environment.PostOffice.Url + '/' + pincode;
    return this.http.get<any[]>(url).pipe(
      map(res => {
        let rtnValue = [];
        if(res.length > 0) {
          const ValueLst = res[0]['PostOffice'];

          ValueLst.forEach((element: any) => {
            const rtnItem = new InnerMapper(PostOffice).map(element);
            rtnValue.push(rtnItem);
          });
        }

        if(!rtnValue) rtnValue = [];

        return rtnValue;
      })
    );
  }
  ...

That wraps up the Model Mapper in Angular

You may also access to source code on GitHub by Click Here

On-road head, we will discuss a lot of things.

Looking forward to your comments and share your feedback.

Until that, I am Lakshman, Signing Off.

Comments

Popular posts from this blog

Implement Logging in Angular with Firebase

RxJS Subject In Angular