Title: NestJS + GraphQL i18n Translations Not Loading Correctly
Description:
I am working on a NestJS + GraphQL application and trying to set up internationalization (i18n) using nestjs-i18n
. However, translations are either not being applied correctly or not loading as expected. The log statement this.i18nService.getSupportedLanguages()
returns an empty array ([]
), which suggests that the translations are not being loaded properly.
Setup
I have configured the i18n module in my app.module.ts
as follows:
app.module.ts
@Module({
imports: [
I18nModule.forRootAsync({
useFactory: () => ({
fallbackLanguage: 'en',
loader: I18nJsonLoader,
loaderOptions: {
path: join(__dirname, '/i18n/'),
watch: true,
},
}),
resolvers: [
{ use: QueryResolver, options: ['lang'] },
AcceptLanguageResolver,
new HeaderResolver(['x-lang']),
],
}),
],
})
export class AppModule {}
Interceptor for Translating Response Messages
I am using an interceptor to modify response messages dynamically:
translate.interceptor.ts
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { I18nService } from 'nestjs-i18n';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class TranslateInterceptor implements NestInterceptor {
constructor(private readonly i18nService: I18nService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const ctx = GqlExecutionContext.create(context);
const req = ctx.getContext().req;
const lang = req.headers['accept-language'] || 'pt-BR';
return next.handle().pipe(
mergeMap(async (responseData) => {
if (typeof responseData === 'object' && responseData.message) {
console.log(
'