Currently, I am working on a NestJS project where my lead assigned me the task of returning different errors to the frontend based on the language in the request header. After some research, I decided to use i18n for this purpose. However, when testing it in postman, instead of returning the message, it displayed the variable name. For example, if there is a variable called "test" with the value "HelloWorld" in the JSON file, it would return "test" instead of "HelloWorld".
I have tried looking for solutions and suggestions on previous posts, revisited the documentation, and even copied code from another project with i18n setup by my lead, but I still can't figure out what's missing. Any help would be greatly appreciated.
I am willing to share relevant files from the project for anyone who can identify the issue.
package.json
{
"name": "nest-experiments",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
...
},
"dependencies": {
...
},
"devDependencies": {
...
},
"jest": {
...
}
}
nest-cli.json
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"assets": [
{ "include": "i18n/**/*", "watchAssets": true }
]
}
}
app.module.ts The code here may differ slightly from the current documentation as it is based on my lead's project.
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import {
AcceptLanguageResolver,
CookieResolver,
HeaderResolver,
I18nJsonLoader,
I18nModule,
QueryResolver,
} from 'nestjs-i18n';
import * as path from 'path';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PointsModule } from './points/points.module';
import { SlackModule } from './slack/slack.module';
import { UsersModule } from './users/users.module';
@Module({
imports: [PointsModule, MongooseModule.forRoot('mongodb+srv://sharbelabousabha:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fada9aca6c7eeafe6acc8a6decbc9fad0dffcf3eaecebfaedafbfb1b4">[email protected]</a>/?retryWrites=true&w=majority'), SlackModule, UsersModule,
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
watch: true,
},
resolvers: [
{ use: QueryResolver, options: ['lang', 'locale', 'l'] },
new HeaderResolver(['x-custom-lang']),
AcceptLanguageResolver,
new CookieResolver(['lang', 'locale', 'l']),
],
})
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
app.service.ts
import { Injectable } from '@nestjs/common';
import { I18nContext, I18nService } from 'nestjs-i18n';
@Injectable()
export class AppService {
constructor(private readonly i18n: I18nService) {}
getHello(): string {
console.log({ lang: I18nContext.current().lang })
return this.i18n.translate('Created.Success');
}
}