Search code examples
nestjsinternationalizationnestjs-i18n

`nestjs-i18n` is not working on custom decorators in NestJs project


I have implemented localization using nestjs-i18n in NestJs. It is working on the controller and service. Its also working on the DTO level, but I am facing issues with custom decorators CustomHeaders or RequestHeaderDto. It's not throwing any error, it's just not giving the correct message, it giving lang.HELLO|{}.

Here are my codes:

// Headers.decorator.ts:

import { CustomHeaders } from '../decorators/header.decorator'
import { ExecutionContext, createParamDecorator } from '@nestjs/common'
export const CustomHeaders = createParamDecorator((data: string | undefined, ctx: ExecutionContext) => {
  const req = ctx.switchToHttp().getRequest()
  if (data) {
    return req.headers[data]
  }
  return req.headers
})

// RequestHeaderDto:

import { IsNotEmpty } from 'class-validator'
import { i18nValidationMessage, I18n } from 'nestjs-i18n'

export class RequestHeaderDto {
  @IsNotEmpty({
    message: i18nValidationMessage('lang.HELLO'),
  })
  t_id: number
}

// controller:

@Get('test')
@UseFilters(new I18nValidationExceptionFilter())
async test(
  @I18n() i18n: any,
  @CustomHeaders() headers: RequestHeaderDto,
): Promise<any> {
    const message = await i18n.t('lang.PRODUCT.NEW',{args: { name: 'Toon' }})
    return message;
}

// Main.ts:

app.useGlobalPipes(new I18nValidationPipe());
  app.useGlobalFilters(new I18nValidationExceptionFilter());

// app.module.ts:

I18nModule.forRootAsync({
      useFactory: (configSrv: NestConfig) => ({
        fallbackLanguage: "en",
        loaderOptions: {
          path: path.join(__dirname, '../i18n/'),
          watch: true,
        },
      }),
      resolvers: [
        { use: QueryResolver, options: ['lang'] },
        new HeaderResolver(['x-lang']),
        AcceptLanguageResolver,
      ],
      inject: [NestConfig],
    })

// src\i18n\en\lang.json

{
  "HELLO": "Hello World",
  "PRODUCT": {
    "NEW": "New Product: {name}"
  },
}

Solution

  • After spending some hours, exploring and hit and try :), I got the solution. We can use nestjs-i18n like this:

    Headers.decorator.ts:

    import { CustomHeaders } from '../decorators/header.decorator'
    import { ExecutionContext, createParamDecorator } from '@nestjs/common'
    
    export const CustomHeaders = createParamDecorator((data: string | undefined, ctx: ExecutionContext) => {
      const req = ctx.switchToHttp().getRequest()
    
      console.log('message:', req.i18nService.t('lang.HELLO', { lang: req.i18nLang, args: { fieldName: 'TEST' }, }))
    
     /** Rest of the codes **
    })
    

    There is no change in controller