如何从nartc/automapper中将配置文件用于nestjs应用程序 [英] How use profiles from nartc/automapper into a nestjs application

查看:168
本文介绍了如何从nartc/automapper中将配置文件用于nestjs应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在NestJS项目中的nartc/automapper lib中将AutoMapper用于nodejs,但是在尝试使用Profiles功能时遇到了麻烦.这是我的配置:

I'm trying to use AutoMapper for nodejs from nartc/automapper lib inside a NestJS project, but I'm having troubles when trying to use Profiles functionality. Here is my configuration:

App.module

App.module

@Module({
  imports: [
    AutomapperModule.withMapper(),
  ],
  controllers: [],
  providers: [],
})
export class AppModule implements NestModule {}

个人资料

@Profile()
export class RoleProfile extends ProfileBase {
  constructor(@InjectMapper() mapper: AutoMapper) {
    super();

    mapper
      .createMap(Role, RoleWithPermissionDto)
      .forMember(
        dest => dest.id,
        mapFrom(src => src.id),
      )
      .forMember(
        dest => dest.name,
        mapFrom(src => src.name),
      )
      .forMember(
        dest => dest.created,
        mapFrom(src => src.createAt),
      )
      .forMember(dest => dest.permissions, ignore());
  }
}

控制器

@Controller('roles')
export class RolesController {
  constructor(private readonly rolesService: RolesService, @InjectMapper() private readonly mapper: AutoMapper) {}

  @Get()
  public async getRoles(@CurrentUser() user: CurrentUserDto) {
    const roles: Role[] = await this.rolesService.findByCompanyId(user.companyId);
    return this.mapper.mapArray(roles, RoleWithPermissionDto);
  }
}

当我调用控制器动作(getRoles)时,会在控制台上收到以下错误消息:

When I call my controller action (getRoles), I get this error message on console:

Mapping not found for source class Role extends base_entity_1.BaseEntity {
} and destination class RoleWithPermissionDto {
    static _OPENAPI_METADATA_FACTORY() {
        return { id: { required: false, type: () => Number }, name: { required: true, type: () => String }, permissions: { required: true, type: () => [require("../permissions/permission.dto").PermissionDto] }, createdAt: { required: true, 
type: () => Date }, created: { required: true, type: () => Date } };
    }
} +5034ms
Error: Mapping not found for source class Role extends base_entity_1.BaseEntity {
} and destination class RoleWithPermissionDto {
    static _OPENAPI_METADATA_FACTORY() {
        return { id: { required: false, type: () => Number }, name: { required: true, type: () => String }, permissions: { required: true, type: () => [require("../permissions/permission.dto").PermissionDto] }, createdAt: { required: true, 
type: () => Date }, created: { required: true, type: () => Date } };
    }
}
    at getMappingForDestination (D:\trabajo\cencogan\project-mercury-api\node_modules\@nartc\automapper\dist\automapper.cjs.development.js:131:11)
    at AutoMapper.mapArray$1 [as mapArray] (D:\trabajo\cencogan\project-mercury-api\node_modules\@nartc\automapper\dist\automapper.cjs.development.js:1262:19)
    at RolesController.getRoles (D:\trabajo\cencogan\project-mercury-api\dist\src\roles\roles.controller.js:35:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)

如果我决定直接在控制器内部创建映射,那么一切都会按预期进行.例如:

If I decide to create the mapping directly inside the controller, everything work as expected. for example:

@Controller('roles')
export class RolesController {
  constructor(private readonly rolesService: RolesService, @InjectMapper() private readonly mapper: AutoMapper) {}

  @Get()
  public async getRoles(@CurrentUser() user: CurrentUserDto) {
    const roles: Role[] = await this.rolesService.findByCompanyId(user.companyId);
    this. mapper
      .createMap(Role, RoleWithPermissionDto)
      .forMember(
        dest => dest.id,
        mapFrom(src => src.id),
      )
      .forMember(
        dest => dest.name,
        mapFrom(src => src.name),
      )
      .forMember(
        dest => dest.created,
        mapFrom(src => src.createAt),
      )
      .forMember(dest => dest.permissions, ignore());
    return this.mapper.mapArray(roles, RoleWithPermissionDto);
  }
}

我以为我的个人资料没有被调用,有人在NestJS项目中使用过这个库吗?

I supposed my Profile is not getting invoked, have anybody used this library in a NestJS project ?

我使用功能模块,因此我的控制器已在RolesModule中注册.

I use feature modules, so my controller is registered inside RolesModule.

感谢您的帮助

推荐答案

我是@nartc/automappernestjsx-automapper的作者,当您正在使用nestjsx-automapper时,它会出现.

I am the author of @nartc/automapper and nestjsx-automapper and it appears as you're using the nestjsx-automapper already.

我没有发现您的设置有任何问题.但是,由于TypeScript的限制,如果在单独的文件中有Profile(在本例中为RoleProfile),则必须RoleProfile导入到其他RoleProfile文件中,保证strong>将执行(Module是最佳位置)

I don't see anything wrong with your setup. However, due to TypeScript limitation, if you have the Profile (in this case, RoleProfile) in a separate file, then you have to import the RoleProfile in some other file that WILL be guaranteed to execute (the Module is the best place)

import './role.profile';

@Module(...)
export class RoleModule {}

如果要将Profile分离到单独的文件中,则需要通过将文件导入某个位置(同样,该模块是个好地方)来确保文件被执行.

If you want to separate Profile out to a separate file, then you need to make sure that file gets executed by importing it somewhere (again, the module is a good place).

我在自述文件中确实提到了这一部分,但似乎并没有足够突出以引起人们的注意.

I did mention this piece in the README but it seems to be not highlighted enough to grab people's attention.

另一件事是您的Profile构造函数中,您不需要@InjectMapper,因为当nestjsx-automapper在内部运行mapper.addProfile()时,mapper将为您传递.

Another thing is in your Profile constructor, you don't need @InjectMapper since mapper will be passed in for you when nestjsx-automapper runs mapper.addProfile() internally.

很抱歉给您带来不便.

这篇关于如何从nartc/automapper中将配置文件用于nestjs应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆