@automapper/ 类
这是官方策略 @automapper tS/ES6级
安装
npm i @automapper/classes
或带有 yarn数字 :
yarn add @automapper/classes
peerDependencies
@automapper/classes 取决于 @automapper/core 财务报告和审定财务报表 reflect-metadata。 。 。 .
npm i @automapper/core reflect-metadata
或带有 yarn数字 :
yarn add @automapper/core reflect-metadata
使用量
@automapper/classes 提供 classes 作为 MappingStrategyInitializer。通过 classes() 改为 createMapper 创建
(单位:千美元) Mapper 用于 classes 战略.
import { classes, AutoMap } from '@automapper/classes';
import { createMapper, createMap, forMember, mapFrom } from '@automapper/core';
const mapper = createMapper({
...,
strategyInitializer: classes()
});
class User {
@AutoMap()
firstName: string;
@AutoMap()
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
class UserDto {
@AutoMap()
firstName: string;
@AutoMap()
lastName: string;
@AutoMap()
fullName: string;
}
createMap(
mapper,
User,
UserDto,
forMember(
d => d.fullName,
mapFrom(s => s.firstName + ' ' + s.lastName)
)
);
mapper.map(new User('Auto', 'Mapper'), User, UserDto);
// UserDto { firstName: 'Auto', lastName: 'Mapper', fullName: 'Auto Mapper' }
自定义
classes() 接受两个可选参数:
-
destinationConstructor:如何构建Destination。这是默认destinationConstructor将用于mapper.mapXXXX()操作.DestinationConstructor是具有下列签名的函数:export type DestinationConstructor< TSource extends Dictionary<TSource> = any, TDestination extends Dictionary<TDestination> = any > = ( sourceObject: TSource, // the sourceObject used to map to the Destination destinationIdentifier: MetadataIdentifier<TDestination> // the Destination model ) => TDestination; // example mapper.map(user, User, UserDto); // sourceObject will be "user" // destinationIdentifier will be "UserDto" // This allows you to provide a default constructor that can be based on the Source object data- 有办法提供一次性习俗
destinationConstructor任何给定的Mapping当你运行时createMap。更多信息 构造
- 有办法提供一次性习俗
-
applyMetadata:战略应如何将元数据应用于模型。 默认对大多数情况都有效,但是如果您想要定制,您可以.ApplyMetadata是具有下列签名的函数:export type ApplyMetadataFn = <TModel extends Dictionary<TModel>>( model: MetadataIdentifier<TModel> ) => TModel; export type ApplyMetadata = ( strategy: MappingStrategy<MetadataIdentifier> ) => ApplyMetadataFn; // for example const customApplyMetadata: ApplyMetadata = (strategy: MappingStrategy) => { // strategy contains the Mapper which stores all the models' metadata return (model) => { // based on this model, you can extract the metadata and do as you like return anObjectThatHasTheMetadataApplied; // { foo: undefined, bar: undefined } }; };
更多信息,请访问 类文档