I have implemented localization using nestjs-i18n
in NestJs. It is working on controller and service.
Its also working on DTO level, but I am facing issue with custom decorators CustomHeaders
or RequestHeaderDto
.
Its not throwing any error, its just not giving the correct message.
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],
})
// srci18nenlang.json
{
"HELLO": "Hello World",
"PRODUCT": {
"NEW": "New Product: {name}"
},
}