Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hodfords-solutions/nestjs-cls-translation
Provides context-aware translations in NestJS using CLS
https://github.com/hodfords-solutions/nestjs-cls-translation
cls nestjs nodejs
Last synced: about 17 hours ago
JSON representation
Provides context-aware translations in NestJS using CLS
- Host: GitHub
- URL: https://github.com/hodfords-solutions/nestjs-cls-translation
- Owner: hodfords-solutions
- Created: 2022-11-02T10:29:00.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-10-08T04:57:28.000Z (4 months ago)
- Last Synced: 2025-01-29T20:15:09.542Z (8 days ago)
- Topics: cls, nestjs, nodejs
- Language: TypeScript
- Homepage: https://opensource.hodfords.uk/nestjs-cls-translation
- Size: 331 KB
- Stars: 47
- Watchers: 0
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
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.
## Installation π€
Install the `nestjs-cls-translation` package with:
```bash
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:
```typescript
TranslationModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(env.ROOT_PATH, 'i18n/'),
watch: true
},
resolvers: [new HeaderResolver(['language'])]
});
```## Usage π
#### Translation Functions
To translate a specific key, use the trans function, passing the key for the translation string you wish to fetch:
```typescript
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.
#### Get Current Language
To retrieve the language currently being used in the context of a request, use the `currentLanguage()` function:
```typescript
const currentLang = currentLanguage()
```#### Get Default Language
If you need to access the application's default or fallback language (set in the module configuration), use the `defaultLanguage()` function:
```typescript
const defaultLang = defaultLanguage()
```#### Run with a Specific Language Context
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:
```typescript
await runInLanguage('en', () => {...});
```## License π
This project is licensed under the MIT License