Skip to content

Latest commit

 

History

History
110 lines (82 loc) · 2.26 KB

README.md

File metadata and controls

110 lines (82 loc) · 2.26 KB

@automapper/classes/mapped-types

@automapper/classes/mapped-types is part of the public API of @automapper/classes.

@automapper/classes/mapped-types is inspired by @nestjs/mapped-types to provide mixins to reduce some boilerplate code.

Usage

All Mapper*Type are exported from @automapper/classes/mapped-types

MapperPickType

MapperPickType accepts an original class, and an array of property keys to pick from the original class.

class Foo {
  @AutoMap()
  foo: string;
  @AutoMap()
  bar: number;
  @AutoMap()
  baz: boolean;
}

class PickFooBar extends MapperPickType(Foo, ['foo', 'bar']) {}

mapper.createMap(Foo, PickFooBar);

const foo = new Foo();
foo.foo = 'foo';
foo.bar = 123;
foo.baz = true;

const pickedFooBar = mapper.map(foo, PickFooBar, Foo);
console.log(pickedFooBar);
/**
 * PickFooBar { foo: 'foo', bar: 123 }
 * only foo and bar have been picked
 */

MapperOmitType

MapperOmitType accepts an original class, and an array of property keys to omit from the original class.

class Foo {
  @AutoMap()
  foo: string;
  @AutoMap()
  bar: number;
  @AutoMap()
  baz: boolean;
}

class OmitFooBar extends MapperOmitType(Foo, ['foo', 'bar']) {}

mapper.createMap(Foo, OmitFooBar);

const foo = new Foo();
foo.foo = 'foo';
foo.bar = 123;
foo.baz = true;

const omittedFooBar = mapper.map(foo, OmitFooBar, Foo);
console.log(omittedFooBar);
/**
 * OmitFooBar { baz: true }
 * foo and bar have been omitted
 */

MapperIntersectionType

MapperIntersectionType accepts two parent classes to receive all properties from both classes.

class Foo {
  @AutoMap()
  foo: string;
}

class Bar {
  @AutoMap()
  bar: number;
}

class IntersectFooBar extends MapperIntersectionType(Foo, Bar) {}

mapper.createMap(IntersectFooBar, Foo);
mapper.createMap(IntersectFooBar, Bar);

const intersect = new IntersectFooBar();
intersect.foo = 'foo';
intersect.bar = 123;

const foo = mapper.map(intersect, Foo, IntersectFooBar);
console.log(foo);
/**
 * Foo { foo: 'foo' }
 */

const bar = mapper.map(intersect, Bar, IntersectFooBar);
console.log(bar);
/**
 * Bar { bar: 123 }
 */

AutoMapper does not have the concept of mapping multiple Sources to a Destination. Hence, please be cautious when to utilize MapperIntersectionType