Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Internationalization Nest js:在异常筛选器中使用I18n服务_Internationalization_Nestjs_Class Validator_Nestjs I18n - Fatal编程技术网

Internationalization Nest js:在异常筛选器中使用I18n服务

Internationalization Nest js:在异常筛选器中使用I18n服务,internationalization,nestjs,class-validator,nestjs-i18n,Internationalization,Nestjs,Class Validator,Nestjs I18n,我有一个nestjs graphql项目。我使用类验证器和nestjs-i18n模块 当按预期注入服务时,我可以使用i18nService。然而,我正在努力做的是在我的ExceptionFilter中使用i18n从class validator处理的ValidationPipe返回翻译后的消息 我现在拥有的 //app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.

我有一个nestjs graphql项目。我使用
类验证器
nestjs-i18n
模块

当按预期注入服务时,我可以使用
i18nService
。然而,我正在努力做的是在我的
ExceptionFilter
中使用i18n从
class validator处理的
ValidationPipe
返回翻译后的消息

我现在拥有的

//app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ItemsModule } from './items/items.module';
import { GraphQLModule } from '@nestjs/graphql';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule } from '@nestjs/config';
import { I18nModule, I18nJsonParser } from 'nestjs-i18n';
import configuration from './config/configuration';
import * as path from 'path';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, load: [configuration] }),
    MongooseModule.forRoot(process.env.MONGO_URI),
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      parser: I18nJsonParser,
      parserOptions: { path: path.join(__dirname, '/i18n/') },
    }),
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      playground: true,
      introspection: true,
      context: ({ req, connection }) =>
        connection ? { req: connection.context } : { req },
    }),
    ItemsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}


我的想法是将i18n密钥传递给类以验证:

import { Field, InputType, } from '@nestjs/graphql';
import { Length } from 'class-validator';

@InputType()
export class ItemToValidate {
  @Length(5, 30, { message: 'global.length' }) //i18n Key
  @Field()
  readonly title: string;
 
}


。。。要像在服务中一样在
AllExceptionsFilter
中使用它,请执行以下操作:

@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private logger: Logger, private i18n: I18nService) {}
  async catch(exception: HttpException) {
   const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const exceptionMessage = (exception) =>
      exception instanceof MongoError
        ? exception?.message
        : exception?.response?.message;
    const translatedMessage = await this.i18n.translate(
      exceptionMessage(exception),
    );
   ...
  }
}


但是,我在boostrap函数中实例化Filter类时出现了一个逻辑错误,因为我不知道如何访问I18N服务并从那里注入它:


async function bootstrap() {
  const logger = new Logger('bootstrap');
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  app.useGlobalFilters(new AllExceptionsFilter(new Logger('Exceptions'), /*I18nService ?*/ ));

}
bootstrap();
实现这一点的最佳方法是什么?

如中所示,如果使用
useGlobalFilters()
注册过滤器,则无法进行依赖项注入

相反,你必须这样做:

从'@nestjs/common'导入{Module};
从'@nestjs/core'导入{APP_FILTER};
@模块({
供应商:[
{
提供:应用程序过滤器,
useClass:AllExceptionsFilter,
},
],
})
导出类AppModule{}
@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private logger: Logger, private i18n: I18nService) {}
  async catch(exception: HttpException) {
   const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const exceptionMessage = (exception) =>
      exception instanceof MongoError
        ? exception?.message
        : exception?.response?.message;
    const translatedMessage = await this.i18n.translate(
      exceptionMessage(exception),
    );
   ...
  }
}



async function bootstrap() {
  const logger = new Logger('bootstrap');
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  app.useGlobalFilters(new AllExceptionsFilter(new Logger('Exceptions'), /*I18nService ?*/ ));

}
bootstrap();