Reputation: 9963
I have a nestjs project and I have implemented localization using nestjs-i18n
. It is working on the controller and service.
It's also working on the DTO level, but I am facing issues with custom pipes.
In the custom pipe, it is undefined. I correctly configured nestjs-i18n
in the project.
Here are my codes:
// Custom Pipe:
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'
import { I18nContext, I18nService } from 'nestjs-i18n';
import { GetRequestQueryDto } from '../dto/request.dto'
@Injectable()
export class ValidationPipe implements PipeTransform {
private readonly i18n: I18nService
transform(value: any, metadata: ArgumentMetadata): GetRequestQueryDto {
switch (metadata.type) {
case 'QUERY':
const message = this.i18n.t('lang.HELLO',{ lang: I18nContext.current()?.lang }) // This is not working
return message;
default:
return value
}
}
}
// Controller:
import { I18n, I18nContext, I18nValidationExceptionFilter } from 'nestjs-i18n'
@Get('test')
@UseFilters(new I18nValidationExceptionFilter())
@UsePipes(new ValidationPipe())
async test(
@I18n() i18n: any,
@CustomHeaders() headers: HeaderDto,
@Query() query: TestDTO
): 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],
})
Upvotes: 0
Views: 158