在Nest.js中将配置文件与nestjsx-automapper一起使用 [英] Using Profiles with nestjsx-automapper in nest.js

查看:85
本文介绍了在Nest.js中将配置文件与nestjsx-automapper一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 nestjsx-automapper (Chau Tran的https://automapper.netlify.app/docs/usages/init/add-profile )(感谢这段很酷的代码).我已经实现了它,如文档中所示,并且已经在此处进行了讨论:如何将配置文件从nartc/automapper应用于nestjs应用程序

I´m using nestjsx-automapper (https://automapper.netlify.app/docs/usages/init/add-profile) by Chau Tran (thanks for that cool piece of code). I´ve implemented it like shown in the documentation and as already discussed here: How use profiles from nartc/automapper into a nestjs application

但是我仍然有一个问题,可以从我的个人资料类中访问AutoMapper .

这是我的设置:

app.module.ts:

import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { MerchantModule } from './merchant/merchant.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AutomapperModule, AutoMapper } from 'nestjsx-automapper';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...
    }),
    AutomapperModule.withMapper(),
    MerchantModule
  ],
  providers: [],
  controllers: [],
})
export class AppModule {}

merchant.module.ts:

import { Module } from '@nestjs/common';
import { MerchantController } from './merchant.controller';
import { MerchantService } from './merchant.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Merchant } from './entities/merchant.entity';
import { MerchantProfile } from './profiles/merchant.profile';
import { AutoMapper, AutomapperModule } from 'nestjsx-automapper';

@Module({
  imports: [TypeOrmModule.forFeature([Merchant]), AutomapperModule, MerchantProfile],
  exports: [TypeOrmModule],
  controllers: [MerchantController],
  providers: [MerchantService]
})
export class MerchantModule {}

merchant.profile.ts:

import {
  ProfileBase,
  Profile,
  AutoMapper
} from 'nestjsx-automapper';
import { Merchant } from '../entities/merchant.entity';
import { MerchantDto } from '../dto/merchant.dto';

@Profile()
export class MerchantProfile extends ProfileBase {
  constructor(
    private readonly mapper: AutoMapper) {
    super();
    mapper.createMap(Merchant, MerchantDto);
  }

    configure(): void {      
      return null;
    }
}

merchant.controller.ts:

merchant.controller.ts:

import { Controller, Get, Param, Post, Body, Put, Delete } from '@nestjs/common';
import { MerchantService } from './merchant.service';
import { Merchant } from './entities/merchant.entity';
import { MerchantDto } from './dto/merchant.dto';
import { DeleteResult } from 'typeorm';
import { AutoMapper, InjectMapper } from 'nestjsx-automapper';

@Controller('merchant')
export class MerchantController {

    constructor(
        private merchantService: MerchantService,
        @InjectMapper() private readonly mapper: AutoMapper) { }

    @Get()
    public async findAll(): Promise<MerchantDto[]> {
        return this.mapper.mapArray(await this.merchantService.find(),MerchantDto);
    }
}

使用此设置运行应用程序时,出现以下异常:嵌套无法解析AutomapperModule(?)的依赖项.请确保在AutomapperModule上下文中索引[0]处的参数AutomapperExplorer可用.

When I run the application with this setup I get the following exception: Nest can't resolve dependencies of the AutomapperModule (?). Please make sure that the argument AutomapperExplorer at index [0] is available in the AutomapperModule context.

推荐答案

AutoMapperModule.withMapper()是您唯一需要使用 AutoMapperModule .

withMapper()创建一个 AutoMapper 的单例,当您要使用时可通过 @InjectMapper()使用 Service (或任何 Injectable )中的Mapper .

withMapper() creates a singleton of AutoMapper that will be available via @InjectMapper() when you want to use the Mapper in a Service (or any Injectable).

关于 Profile ,以下是正确的语法:

As for Profile, the following is the correct syntax:

@Profile()
export class MerchantProfile extends ProfileBase {
  constructor(mapper: AutoMapper) { // no private readonly.
    super();
    mapper.createMap(Merchant, MerchantDto);
  }
  // no configure() method
}

以下是 @ nartc/automapper 源代码,其中编写了 addProfile():

The following is the @nartc/automapper source code where addProfile() is written:

addProfile(profile: new (mapper: AutoMapper) => MappingProfile): AutoMapper {
    this._profileStorage.add(this, new profile(this));
    return this;
}

您可以看到,在内部, @ nartc/automapper 将实例化( new profile())并将 AutoMapper 实例传递给个人资料的构造函数,以便您可以在个人资料的构造函数

You can see that internally, @nartc/automapper will instantiate (new profile()) and pass in the AutoMapper instance to the Profile's constructor so that will be available for you inside of the Profile's constructor

对于您的 MerchantModule

import { Module } from '@nestjs/common';
import { MerchantController } from './merchant.controller';
import { MerchantService } from './merchant.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Merchant } from './entities/merchant.entity';
// import { MerchantProfile } from './profiles/merchant.profile';
// this is all you need which is to import the profile so TypeScript can execute it. Don't need `MerchantProfile` at all
import './profiles/merchant.profile';
import { AutoMapper, AutomapperModule } from 'nestjsx-automapper';

@Module({
  imports: [TypeOrmModule.forFeature([Merchant])], // don't need to import AutoMapperModule again. MerchantProfile is not a Module so you can't import it
  exports: [TypeOrmModule],
  controllers: [MerchantController],
  providers: [MerchantService]
})
export class MerchantModule {}

在您的 MerchantController 中:

@Controller('merchant')
export class MerchantController {

    constructor(
        private merchantService: MerchantService,
        @InjectMapper() private readonly mapper: AutoMapper) { }

    @Get()
    public async findAll(): Promise<MerchantDto[]> {
        // make sure `this.merchantService.find()` returns an Array of 
        // Merchant instances. If not, please provide an extra param to map()
        // return this.mapper.mapArray(await this.merchantService.find(),MerchantDto);
        return this.mapper.mapArray(await this.merchantService.find(), MerchantDto, Merchant); // notice the 3rd parameter is the Source model.
    }
}

请告诉我这是否适合您.如果没有,请在 nestjsx-automapper 存储库中创建问题,并提供可复制的存储库,我将尽快进行调查.

Please let me know if this works for you. If not, please create an issue in nestjsx-automapper repo and provide a reproducible repository, I'll take a look as soon as possible.

这篇关于在Nest.js中将配置文件与nestjsx-automapper一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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