();
console.log('current language', i18n.lang);
response
.status(500)
.send(`Your language is: ${i18n.lang}`);
}
}
```
--------------------------------
### createAsync() Static Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md
Creates an I18nContext instance asynchronously.
```APIDOC
### createAsync()
> `static` **createAsync**<`T`>(`ctx`, `next`): `Promise` <`T`>
#### Type Parameters
##### T
`T`
#### Parameters
##### ctx
`I18nContext`
##### next
(...`args`) => `Promise` <`T`>
#### Returns
`Promise` <`T`>
```
--------------------------------
### forRoot()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nModule.md
Static method to configure the I18nModule with options.
```APIDOC
## forRoot()
> `static` **forRoot**(`options`): `DynamicModule`
#### Parameters
##### options
[`I18nOptions`](../interfaces/I18nOptions.md)
#### Returns
`DynamicModule`
```
--------------------------------
### Use Debug Language for Translation Keys
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/debugging.md
When debugging, set the language to `debug` to get the translation key instead of the translated string. This helps in verifying that the correct keys are being used.
```typescript
i18n.t('test.HELLO', {args: { username: 'Toon' }, lang: 'debug'})
// => test.HELLO
```
--------------------------------
### configure()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nModule.md
Configures the middleware consumer for the I18nModule.
```APIDOC
## configure()
> **configure**(`consumer`): `void`
#### Parameters
##### consumer
`NestMiddlewareConsumer`
#### Returns
`void`
#### Implementation of
`NestModule.configure`
```
--------------------------------
### onModuleInit()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nModule.md
Lifecycle hook called when the module is initialized.
```APIDOC
## onModuleInit()
> **onModuleInit**(): `Promise`<`void`>
#### Returns
`Promise`<`void`>
#### Implementation of
`OnModuleInit.onModuleInit`
```
--------------------------------
### Example Validation Error Response
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/dto_validation/global-validation.md
This JSON structure represents a typical validation error response when using global validation with translated messages. It details the properties that failed validation and the specific constraints that were violated.
```json
{
"statusCode": 400,
"errors": [
{
"property": "email",
"children": [],
"constraints": {
"isEmail": "email is invalid",
"isNotEmpty": "email cannot be empty"
}
},
{
"property": "password",
"children": [],
"constraints": { "isNotEmpty": "password cannot be empty" }
},
{
"property": "extra",
"children": [
{
"property": "subscribeToEmail",
"children": [],
"constraints": {
"isBoolean": "subscribeToEmail is not a boolean"
}
},
{
"property": "min",
"children": [],
"constraints": {
"min": "min with value: \"1\" needs to be at least 5, ow and COOL"
}
},
{
"property": "max",
"children": [],
"constraints": {
"max": "max with value: \"100\" needs to be less than 10, ow and SUPER"
}
}
],
"constraints": {}
}
]
}
```
--------------------------------
### Translate Nested Translations Without Arguments
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/faq/common.md
When translating nested values without arguments, you might initially get the translation string with the placeholder. Pass an empty arguments object to resolve the nested translation.
```json
// translations.json
{
"nestedValue": "world",
"foo": "Hello $t(translations.nestedValue)"
}
```
```typescript
// foo.service.ts
i18n.translate("translations.foo") // result: "Hello $t(translations.nestedValue)"
// to get the actual translations , just pass in empty args
i18n.translate("translations.foo", { args: {} }) // result: "Hello world"
```
--------------------------------
### GraphQLWebsocketResolver Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/GraphQLWebsocketResolver.md
Initializes a new instance of the GraphQLWebsocketResolver class.
```APIDOC
## new GraphQLWebsocketResolver()
### Description
Initializes a new instance of the `GraphQLWebsocketResolver` class.
### Returns
- `GraphQLWebsocketResolver`: An instance of the resolver.
```
--------------------------------
### Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nJsonLoader.md
Initializes a new instance of the I18nJsonLoader class. It accepts options that are passed to the base class constructor.
```APIDOC
## new I18nJsonLoader(options: I18nAbstractLoaderOptions): I18nJsonLoader
### Parameters
#### options
- **options** (I18nAbstractLoaderOptions) - Options for the loader.
### Returns
- I18nJsonLoader - An instance of the I18nJsonLoader.
```
--------------------------------
### gRPC Controller with i18n Payload
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/grpc.md
Use the `@Payload()` decorator for the data argument within your gRPC controller methods to ensure data is passed correctly. This example demonstrates fetching a hero and using i18n for a username.
```typescript
@GrpcMethod('HeroesService', 'FindOne')
findOne(@Payload() data: HeroById, @I18n() i18n: I18nContext): Hero {
const items = [
{
id: 1,
name: i18n.t('test.set-up-password.heading', {
args: { username: 'John' },
}),
},
{ id: 2, name: 'Doe' },
];
return items.find(({ id }) => id === data.id);
}
```
--------------------------------
### QueryResolver Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/QueryResolver.md
Initializes a new instance of the QueryResolver class. It can optionally accept an array of keys.
```APIDOC
## Constructor
> **new QueryResolver**(`keys?`): `QueryResolver`
#### Parameters
##### keys?
`string`[] = `[]`
#### Returns
`QueryResolver`
```
--------------------------------
### Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationPipe.md
Initializes a new instance of the I18nValidationPipe class. It accepts optional options to configure its behavior.
```APIDOC
## Constructor
> **new I18nValidationPipe**(`options?`): `I18nValidationPipe`
#### Parameters
##### options?
[`I18nValidationPipeOptions`](../type-aliases/I18nValidationPipeOptions.md)
#### Returns
`I18nValidationPipe`
```
--------------------------------
### I18nLoader Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nLoader.md
Initializes a new instance of the I18nLoader class. This is an abstract class, so direct instantiation is not typical; it's meant to be extended.
```APIDOC
## Constructor
> **new I18nLoader**(): `I18nLoader`
#### Returns
`I18nLoader`
```
--------------------------------
### viewEngine
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/I18nOptions.md
Optional string specifying the view engine to use for rendering i18n views.
```APIDOC
## viewEngine
### Description
Optional string that specifies which view engine should be used for rendering internationalized views. This allows integration with different templating engines.
### Type
[`I18nViewEngine`](../type-aliases/I18nViewEngine.md)
### Optional
Yes
```
--------------------------------
### Configure Pug View Engine
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/pug.md
Enable Pug support by setting the `viewEngine` option in the `I18nModule.forRoot()` configuration.
```typescript
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
},
viewEngine: 'pug'
})
```
--------------------------------
### forRootAsync()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nModule.md
Static method to configure the I18nModule asynchronously with options.
```APIDOC
## forRootAsync()
> `static` **forRootAsync**(`options`): `DynamicModule`
#### Parameters
##### options
[`I18nAsyncOptions`](../interfaces/I18nAsyncOptions.md)
#### Returns
`DynamicModule`
```
--------------------------------
### translate() Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/I18nTranslator.md
Translates a given key to a string, optionally with provided options. This is the primary method for retrieving translated strings.
```APIDOC
## translate()
### Description
Translates a given key to a string, optionally with provided options. This is the primary method for retrieving translated strings.
### Method Signature
`translate(key: P, options?: TranslateOptions): IfAnyOrNever`
### Parameters
#### key
- **key** (P) - The translation key to look up.
#### options?
- **options** (TranslateOptions) - Optional. An object containing options for translation, such as interpolation values.
### Returns
- `IfAnyOrNever` - The translated string or the original key if translation fails or is not applicable.
```
--------------------------------
### Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationExceptionFilter.md
Initializes a new instance of the I18nValidationExceptionFilter class. It accepts optional configuration options.
```APIDOC
## Constructor
> **new I18nValidationExceptionFilter**(`options?`): `I18nValidationExceptionFilter`
#### Parameters
##### options?
`I18nValidationExceptionFilterOptions` = `...`
#### Returns
`I18nValidationExceptionFilter`
```
--------------------------------
### Properties
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md
Properties available on the I18nContext instance.
```APIDOC
## Properties
### id
> `readonly` **id**: `number`
***
### lang
> `readonly` **lang**: `string`
***
### messageFormat
> `readonly` **messageFormat**: `I18nMessageFormat`
***
### service
> `readonly` **service**: [`I18nService`](I18nService.md)<`K`>
```
--------------------------------
### Configure Subfolder Loading
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/loader.md
Enable loading translations from subfolders by setting `includeSubfolders: true` in the loader options.
```typescript
I18nModule.forRoot({
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
includeSubfolders: true,
},
})
```
--------------------------------
### current() Static Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md
Retrieves the current I18nContext instance, optionally from a given ArgumentsHost.
```APIDOC
### current()
> `static` **current**<`K`>(`context?`): `I18nContext` <`K`>
#### Type Parameters
##### K
`K` = `Record` <`string`, `unknown`
#### Parameters
##### context?
`ArgumentsHost`
#### Returns
`I18nContext` <`K`>
```
--------------------------------
### Configure Assets with outDir in nest-cli.json
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx
When using a monorepo, specify the `outDir` for assets in `nest-cli.json` to ensure correct copying to the distribution directory.
```json
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{
"include": "i18n/**/*",
"watchAssets": true,
"outDir": "dist/apps/api"
}
]
}
}
```
--------------------------------
### prepareStackTrace Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
The static prepareStackTrace method is used for customizing stack traces. It is inherited from HttpException.
```APIDOC
## prepareStackTrace()
### Description
Customizes stack traces.
### Method
`static prepareStackTrace(err: Error, stackTraces: CallSite[]): any`
### Parameters
#### Parameters
- **err** (Error) - The error object.
- **stackTraces** (CallSite[]) - An array of call site objects representing the stack traces.
### Returns
`any` - The customized stack trace.
### See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
### Inherited from
`HttpException.prepareStackTrace`
```
--------------------------------
### load()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nAbstractLoader.md
Loads translations from the source.
```APIDOC
## load()
> **load**(): `Promise` <[`I18nTranslation`](../interfaces/I18nTranslation.md) | `Observable` <[`I18nTranslation`](../interfaces/I18nTranslation.md)
#### Returns
`Promise` <[`I18nTranslation`](../interfaces/I18nTranslation.md) | `Observable` <[`I18nTranslation`](../interfaces/I18nTranslation.md)
#### Overrides
[`I18nLoader`](I18nLoader.md).[`load`](I18nLoader.md#load)
```
--------------------------------
### Bootstrap Eta Engine with Express
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/eta.md
Manually wire up the Eta engine with the underlying Express app in your NestJS bootstrap process. This involves setting up Eta, defining the views directory, and registering the engine with Express.
```typescript
import { Eta } from 'eta';
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create(AppModule, ExpressAdapter);
const viewsDir = join(__dirname, '..', 'views');
const eta = new Eta({ views: viewsDir });
const expressApp = app.getHttpAdapter().getInstance();
expressApp.engine('eta', buildEtaEngine(eta));
expressApp.set('view engine', 'eta');
expressApp.set('views', viewsDir);
await app.listen(3000);
}
function buildEtaEngine(eta: Eta) {
return (filePath, data, cb) => {
try {
const fileContent = eta.readFile(filePath);
const renderedTemplate = eta.renderString(fileContent, data);
cb(null, renderedTemplate);
} catch (error) {
cb(error);
}
};
}
```
--------------------------------
### Configure Nunjucks with Express
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/nunjucks.md
Set up Nunjucks for Express applications by configuring the view directory, autoescaping, caching, and associating it with the Express instance.
```typescript
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const viewsDir = join(__dirname, '..', 'views');
const nunjucks = require('nunjucks');
const expressApp = app.getHttpAdapter().getInstance();
nunjucks.configure(viewsDir, {
autoescape: true,
noCache: true,
express: expressApp,
});
app.setBaseViewsDir(viewsDir);
app.setViewEngine('njk');
await app.listen(3000);
}
```
--------------------------------
### Configure GraphQLModule for subscriptions-transport-ws
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/graphql.md
If you are still using `subscriptions-transport-ws`, reconfigure your `GraphQLModule` to include `onConnect` and `path` within the subscription configuration. It is recommended to migrate to `graphql-ws`.
```typescript
GraphQLModule.forRoot({
driver: ApolloDriver,
subscriptions: {
'subscriptions-transport-ws': {
onConnect: (params) => ({ connectionParams: params }),
path: '/graphql'
}
},
typePaths: ['*/**/*.graphql'],
context: (ctx) => ctx,
path: '/graphql',
})
```
--------------------------------
### Configure EJS View Engine in AppModule
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/ejs.md
Enable EJS support by setting the `viewEngine` option in the `I18nModule.forRoot` configuration.
```diff
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
},
+ viewEngine: 'ejs'
})
```
--------------------------------
### getDefaultOptions()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nYamlLoader.md
Retrieves the default options for the loader. This method overrides the base implementation.
```APIDOC
## getDefaultOptions()
> **getDefaultOptions**(): `Partial`
### Returns
- `Partial`
```
--------------------------------
### Configure Assets in nest-cli.json
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx
Ensure the i18n translation files are copied to the dist folder during the build process by configuring `assets` in `nest-cli.json`.
```json
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{ "include": "i18n/**/*", "watchAssets": true }
]
}
}
```
--------------------------------
### Configure Multiple Loaders
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/loader.md
Provide an array of pre-instantiated loader objects to the `loaders` option. Translations and languages from all loaders are deep-merged.
```typescript
I18nModule.forRoot({
fallbackLanguage: 'en',
loaders: [
new I18nJsonLoader({ path: path.join(__dirname, '/i18n/') }),
new MyDatabaseLoader(),
],
})
```
--------------------------------
### resolve Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/GrpcMetadataResolver.md
Resolves internationalization keys from the gRPC context.
```APIDOC
## resolve Method
> **resolve**(`context`): `Promise`\<`string` \| `string`[]\>
#### Parameters
##### context
`ExecutionContext`
#### Returns
`Promise`\<`string` \| `string`[]\>
#### Implementation of
[`I18nResolver`](../interfaces/I18nResolver.md).[`resolve`](../interfaces/I18nResolver.md#resolve)
```
--------------------------------
### Run NestJS Tests
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/samples/simple/README.md
Commands for executing unit tests, end-to-end (e2e) tests, and generating test coverage reports.
```bash
pnpm run test
```
```bash
pnpm run test:e2e
```
```bash
pnpm run test:cov
```
--------------------------------
### Configure GraphQLModule for graphql-ws Subscriptions
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/graphql.md
Add the `context` option to your `GraphQLModule` configuration when using `graphql-ws` for subscriptions. This ensures context is passed correctly.
```typescript
GraphQLModule.forRoot({
driver: ApolloDriver,
subscriptions: {
'graphql-ws': true,
},
typePaths: ['*/**/*.graphql'],
context: (ctx) => ctx,
path: '/graphql',
})
```
--------------------------------
### load()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nYamlLoader.md
Loads the translations. Inherited from I18nAbstractLoader.
```APIDOC
## load()
> **load**(): `Promise`
### Returns
- `Promise`
```
--------------------------------
### HeaderResolver Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/HeaderResolver.md
Initializes a new instance of the HeaderResolver class. Optionally accepts an array of header keys to look for.
```APIDOC
## Constructor
> **new HeaderResolver**(`keys?`): `HeaderResolver`
#### Parameters
##### keys?
- `string[]` - Optional. An array of header keys to search for. Defaults to an empty array.
```
--------------------------------
### Configure Eta View Engine in AppModule
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/eta.md
Register the Eta engine with the I18nModule by setting `viewEngine: 'eta'`. This tells the module to use Eta for rendering views.
```typescript
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
},
viewEngine: 'eta',
}),
```
--------------------------------
### Capture Stack Trace - Basic Usage
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
Creates a .stack property on an object. The optional constructorOpt argument can be used to omit frames from the stack trace.
```javascript
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
```
--------------------------------
### Configure I18nModule and MailerModule
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/mailer.md
Register the 't' helper on the Handlebars adapter using 'i18n.hbsHelper' and configure MailerModule with the correct template directory and adapter.
```typescript
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { I18nModule, I18nService, HeaderResolver } from 'nestjs-i18n';
import path from 'path';
@Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
watch: true,
},
resolvers: [new HeaderResolver(['x-lang'])],
}),
MailerModule.forRootAsync({
inject: [I18nService],
useFactory: (i18n: I18nService) => ({
transport: {
// your SMTP config
},
defaults: {
from: '"No Reply" ',
},
template: {
dir: path.join(__dirname, 'mail/templates'),
adapter: new HandlebarsAdapter({ t: i18n.hbsHelper }),
options: {
strict: true,
},
},
}),
}),
],
})
export class AppModule {}
```
--------------------------------
### t() Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md
Translates a given key to its corresponding string in the current language. Supports type-safe path access and options for interpolation.
```APIDOC
## Methods
### t()
> **t**<`P`, `R`>(`key`, `options?`): `IfAnyOrNever` <`R`, `string`, `R`>
#### Type Parameters
##### P
`P` *extends* `string` = `any`
##### R
`R` = [`PathValue`](../type-aliases/PathValue.md)<`K`, `P`>
#### Parameters
##### key
`P`
##### options?
[`TranslateOptions`](../interfaces/TranslateOptions.md)
#### Returns
`IfAnyOrNever` <`R`, `string`, `R`>
```
--------------------------------
### hbsHelper()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nService.md
Provides a helper function for Handlebars to perform translations.
```APIDOC
## hbsHelper()
### Signature
```typescript
hbsHelper(key: string, args: any, options: any): string
```
### Parameters
- **key** (`string`): The translation key.
- **args** (`any`): Arguments for the translation.
- **options** (`any`): Handlebars options.
### Returns
- `string`: The translated string.
```
--------------------------------
### I18nMiddleware use Method
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nMiddleware.md
The core method of the middleware that processes incoming requests to handle internationalization.
```APIDOC
## use()
> **use**(`req`, `res`, `next`): `Promise`<`any`>
#### Parameters
##### req
`any`
##### res
`any`
##### next
`any`
#### Returns
`Promise`<`any`>
#### Implementation of
`NestMiddleware.use`
```
--------------------------------
### OptionsProvider Interface
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/OptionsProvider.md
The OptionsProvider interface is used to configure the i18n options. It has a single property 'options' which can be of any type, allowing for flexible configuration.
```APIDOC
## Interface: OptionsProvider
### Properties
#### options
- **options** (any) - Description: Configuration options for i18n.
```
--------------------------------
### typesOutputPath
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/I18nOptions.md
Optional string specifying the output path for generated TypeScript types.
```APIDOC
## typesOutputPath
### Description
Optional string that specifies the directory where the generated TypeScript types for translations should be saved. This is useful for improving type safety in your application.
### Type
`string`
### Optional
Yes
```
--------------------------------
### Enable Watch Mode for Loaders
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/loader.md
Enable live updates for loaders by returning an `Observable` from `languages()` or `load()`. Use `watch: true` in loader options for file-based loaders.
```typescript
new I18nJsonLoader({
path: path.join(__dirname, '/i18n/'),
watch: true,
})
```
--------------------------------
### Configure custom formatter in AppModule
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/formatting.md
To implement a custom formatting logic, define the `formatter` option within the `I18nModule.forRoot` configuration. This function receives the template string and arguments.
```typescript
import { Module } from '@nestjs/common';
import path from 'path';
import { I18nJsonLoader, I18nModule } from 'nestjs-i18n';
@Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
formatter: (template: string, ...args: any[]) => template,
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
watch: true,
}
}),
],
controllers: [],
})
export class AppModule {}
```
--------------------------------
### Capture Stack Trace - Omitting Frames
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
Demonstrates how to use the constructorOpt argument to hide implementation details from the error stack trace. Frames above the specified constructor function are omitted.
```javascript
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
```
--------------------------------
### getHttpExceptionOptionsFrom()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
Retrieves the HttpExceptionOptions from a given argument, which can be a string or an HttpExceptionOptions object.
```APIDOC
## getHttpExceptionOptionsFrom()
### Description
Retrieves the HttpExceptionOptions from a given argument, which can be a string or an HttpExceptionOptions object.
### Method
`static` getHttpExceptionOptionsFrom
### Parameters
#### descriptionOrOptions
- `string` | `HttpExceptionOptions` - The input from which to extract the options.
### Returns
- `HttpExceptionOptions` - The extracted HTTP exception options.
### Inherited from
`HttpException.getHttpExceptionOptionsFrom`
```
--------------------------------
### getSupportedLanguages()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nService.md
Retrieves the list of currently supported languages.
```APIDOC
## getSupportedLanguages()
### Signature
```typescript
getSupportedLanguages(): string[]
```
### Returns
- `string[]`: An array of supported language codes.
```
--------------------------------
### load()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nLoader.md
Abstract method to load translation data. Implementations should return a Promise resolving to an I18nTranslation object or an Observable emitting an I18nTranslation object.
```APIDOC
## load()
> `abstract` **load**(): `Promise`<[`I18nTranslation`](../interfaces/I18nTranslation.md) | `Observable`<[`I18nTranslation`](../interfaces/I18nTranslation.md)>>
Defined in: [src/loaders/i18n.loader.ts:6](https://github.com/toonvanstrijp/nestjs-i18n/blob/4e4ebce513fdde29fadb2358f8753744e6022935/src/loaders/i18n.loader.ts#L6)
#### Returns
`Promise`<[`I18nTranslation`](../interfaces/I18nTranslation.md) | `Observable`<[`I18nTranslation`](../interfaces/I18nTranslation.md)>>
```
--------------------------------
### useICU
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/I18nOptions.md
Optional boolean to enable ICU message format support. Defaults to false.
```APIDOC
## useICU
### Description
Optional boolean to enable support for the ICU message format. If set to true, you can use ICU syntax for more complex message formatting, including pluralization and gender.
### Type
`boolean`
### Optional
Yes
```
--------------------------------
### Custom Loader Implementation
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/loader.md
Extend the `I18nLoader` abstract class to create a custom loader. Implement `languages()` to return supported language codes and `load()` to return translations.
```typescript
import { I18nLoader } from 'nestjs-i18n';
import { I18nTranslation } from 'nestjs-i18n';
export class MyDatabaseLoader extends I18nLoader {
async languages(): Promise {
// fetch language codes from your data source
return ['en', 'nl'];
}
async load(): Promise {
// fetch and return translations keyed by language
return {
en: { greeting: 'Hello' },
nl: { greeting: 'Hallo' },
};
}
}
```
--------------------------------
### getDefaultOptions()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nJsonLoader.md
Retrieves the default options for the I18nJsonLoader. This method overrides the base class method to provide JSON-specific defaults.
```APIDOC
## getDefaultOptions(): Partial
### Returns
- Partial - The default options for the loader.
```
--------------------------------
### extractDescriptionAndOptionsFrom()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
Utility method used to extract the error description and httpExceptionOptions from the given argument. This is used by inheriting classes to correctly parse both options.
```APIDOC
## extractDescriptionAndOptionsFrom()
### Description
Utility method used to extract the error description and httpExceptionOptions from the given argument. This is used by inheriting classes to correctly parse both options.
### Method
`static` extractDescriptionAndOptionsFrom
### Parameters
#### descriptionOrOptions
- `string` | `HttpExceptionOptions` - The input that may contain a description or options.
### Returns
- `DescriptionAndOptions` - An object containing the error description and httpExceptionOptions.
### Inherited from
`HttpException.extractDescriptionAndOptionsFrom`
```
--------------------------------
### ResolverWithOptionsBase
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/interfaces/ResolverWithOptionsBase.md
The ResolverWithOptionsBase interface is used to configure i18n resolvers with options.
```APIDOC
## Interface: ResolverWithOptionsBase
### Description
This interface defines the base options for i18n resolvers.
### Properties
#### use
- **use** (Type) - Required - Specifies the i18n resolver class to use.
```
--------------------------------
### getDescriptionFrom()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nValidationException.md
Retrieves the error description from a given argument, which can be a string or an HttpExceptionOptions object.
```APIDOC
## getDescriptionFrom()
### Description
Retrieves the error description from a given argument, which can be a string or an HttpExceptionOptions object.
### Method
`static` getDescriptionFrom
### Parameters
#### descriptionOrOptions
- `string` | `HttpExceptionOptions` - The input from which to extract the description.
### Returns
- `string` - The extracted error description.
### Inherited from
`HttpException.getDescriptionFrom`
```
--------------------------------
### CookieResolver Constructor
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/CookieResolver.md
Initializes a new instance of the CookieResolver class. Optionally accepts an array of cookie names to look for.
```APIDOC
## Constructor
### Signature
```typescript
new CookieResolver(cookieNames?: string[])
```
### Parameters
- **cookieNames?** (`string[]`) - Optional. An array of cookie names to search for the locale.
```
--------------------------------
### languages()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nLoader.md
Abstract method to retrieve a list of available language codes. Implementations should return a Promise resolving to an array of strings or an Observable emitting an array of strings.
```APIDOC
## languages()
> `abstract` **languages**(): `Promise`<`string`[] | `Observable`<`string`[]>>
Defined in: [src/loaders/i18n.loader.ts:5](https://github.com/toonvanstrijp/nestjs-i18n/blob/4e4ebce513fdde29fadb2358f8753744e6022935/src/loaders/i18n.loader.ts#L5)
#### Returns
`Promise`<`string`[] | `Observable`<`string`[]>>
```
--------------------------------
### Register I18nMiddleware Globally in main.ts
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/exception-filters.md
Register the `I18nMiddleware` globally in your `main.ts` file to ensure it's applied before any exceptions are thrown, especially when dealing with exceptions originating from middleware.
```typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { I18nMiddleware } from 'nestjs-i18n';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(I18nMiddleware);
await app.listen(3000);
}
bootstrap();
```
--------------------------------
### languages()
Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nAbstractLoader.md
Retrieves the available languages supported by the loader.
```APIDOC
## languages()
> **languages**(): `Promise` <`string`[] | `Observable` <`string`[]
#### Returns
`Promise` <`string`[] | `Observable` <`string`[]
#### Overrides
[`I18nLoader`](I18nLoader.md).[`languages`](I18nLoader.md#languages)
```