nestjs-cls-translation provides context-aware translations in NestJS applications using Context-Local Storage (CLS), making it easier to manage and access locale-specific data across different parts of your application.
Install the nestjs-cls-translation
package with:
npm install @hodfords/nestjs-cls-translation --save
You'll need to configure the translation module by adding it to your NestJS app's module setup. Hereβs how you can configure it:
TranslationModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(env.ROOT_PATH, 'i18n/'),
watch: true
},
resolvers: [new HeaderResolver(['language'])]
});
To translate a specific key, use the trans function, passing the key for the translation string you wish to fetch:
const translatedText = trans('error.an_error_occurred')
This will return the translated string based on the user's current language, or the fallback language if no specific translation exists for the user's language.
To retrieve the language currently being used in the context of a request, use the currentLanguage()
function:
const currentLang = currentLanguage()
If you need to access the application's default or fallback language (set in the module configuration), use the defaultLanguage()
function:
const defaultLang = defaultLanguage()
You may want to execute certain parts of your code in a specific language context. The runInLanguage() function allows you to run a block of code under a designated language context, overriding the current language:
await runInLanguage('en', () => {...});
This project is licensed under the MIT License