### Install Eta Package Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/eta.md Install the Eta package using npm. This is the first step to using Eta as your view engine. ```bash npm install eta ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/samples/simple/README.md Use this command to install all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Example Translation File Structure Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/nested.md This example demonstrates how nested translations and argument passing appear in a typical translation file. ```json { "HELLO": "World", "WELCOME": "Hello {username}", "PAGE_HOME": { "TITLE": "Home to this $t(auth.HELLO)", "SUBTITLE": "$t(auth.WELCOME, {{ \"username\": \"{username}\" }}) this is the home page" } } ``` -------------------------------- ### Install nestjs-i18n Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Install the nestjs-i18n package using npm. ```bash npm install --save nestjs-i18n ``` -------------------------------- ### Basic Module Setup with I18nModule.forRoot Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Configure the `I18nModule` synchronously in your `AppModule` by specifying the fallback language and the path to your translation files. ```typescript import { Module } from '@nestjs/common'; import path from 'path'; import { I18nModule } from 'nestjs-i18n'; @Module({ imports: [ I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), watch: true, }, }), ], controllers: [], }) export class AppModule {} ``` -------------------------------- ### Run NestJS Application Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/samples/simple/README.md Commands to start the NestJS application in different modes. Use 'start:dev' for development with watch mode and 'start:prod' for production. ```bash pnpm run start ``` ```bash pnpm run start:dev ``` ```bash pnpm run start:prod ``` -------------------------------- ### Example Translation Key with Subfolders Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/loader.md When subfolders are enabled, use a dot-separated path prefix for translation keys corresponding to the folder structure. ```json { "HELLO": "World" } ``` -------------------------------- ### Configure Handlebars View Engine (Fastify) Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/handlebars.md For Fastify, use 'handlebars' as the `viewEngine` value. Install 'handlebars' (`npm i handlebars`). ```typescript I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), }, viewEngine: 'handlebars' }) ``` -------------------------------- ### Async Module Setup with I18nModule.forRootAsync Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Configure the `I18nModule` asynchronously using `forRootAsync`. This allows for dependency injection and dynamic configuration, such as loading the fallback language from environment variables. ```typescript import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import path from 'path'; import { I18nModule, AcceptLanguageResolver, QueryResolver, HeaderResolver } from 'nestjs-i18n'; @Module({ imports: [ I18nModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ fallbackLanguage: configService.getOrThrow('FALLBACK_LANGUAGE'), loaderOptions: { path: path.join(__dirname, '/i18n/'), watch: true, }, }), resolvers: [ { use: QueryResolver, options: ['lang'] }, AcceptLanguageResolver, new HeaderResolver(['x-lang']), ], inject: [ConfigService], }), ], controllers: [], }) export class AppModule {} ``` -------------------------------- ### Configure I18nModule with Resolvers Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Register the I18nModule in your root module using `forRoot`. This example demonstrates setting a fallback language, configuring the JSON loader with watch mode, and adding Query and Accept-Language resolvers. ```typescript import { Module } from '@nestjs/common'; import path from 'path'; import { AcceptLanguageResolver, I18nJsonLoader, I18nModule, QueryResolver, } from 'nestjs-i18n'; @Module({ imports: [ I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), watch: true, }, resolvers: [ { use: QueryResolver, options: ['lang'] }, AcceptLanguageResolver, ], }), ], controllers: [], }) ``` -------------------------------- ### Example Translation File Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Define translations in JSON format for different languages. Supports nested objects, arrays, and variable interpolation. ```json { "HELLO": "Hello", "PRODUCT": { "NEW": "New Product: {name}" }, "ENGLISH": "English", "ARRAY": ["ONE", "TWO", "THREE"], "cat": "Cat", "cat_name": "Cat: {name}", "set-up-password": { "heading": "Hello, {username}", "title": "Forgot password", "followLink": "Please follow the link to set up your password" }, "day_interval": { "one": "Every day", "other": "Every {count} days", "zero": "Never" }, "nested": "We go shopping: $t(test.day_interval, {{"count": {count} }})" } ``` -------------------------------- ### Pug Translation Example Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/pug.md Demonstrates how to use the `t` function within a Pug template to render translated strings, including dynamic arguments. The current language must be passed manually as the second argument. ```json { "HELLO": "Hello {username}" } ``` ```typescript @Controller('Test') export class TestController { @Get('/') @Render('page') index(): any { return { username: "Toon" }; } } ``` ```pug h1 #{t('test.HELLO', i18nLang, {username: username} )} ``` ```html

Hello Toon

``` -------------------------------- ### EJS Translation Example Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/ejs.md Render translated strings within an EJS template, passing the current language and any necessary arguments. ```json { "HELLO": "Hello {username}" } ``` ```typescript import { Controller, Get, Render } from '@nestjs/common'; @Controller('Test') export class TestController { @Get('/') @Render('page') index(): any { return { username: "Toon" }; } } ``` ```ejs

<%= t('test.HELLO', i18nLang, { username }) -%>

``` -------------------------------- ### Eta Template Usage Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/eta.md An example of an Eta template (`.eta` file) that uses the `t` and `i18nLang` variables available on the `it` object to render a translated string. The `username` variable is also accessible. ```html <%= it.t('test.HELLO', it.i18nLang) %> ``` -------------------------------- ### Configure Handlebars View Engine (Express) Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/handlebars.md Enable Handlebars support in the I18nModule by setting the `viewEngine` option to 'hbs'. Ensure 'hbs' is installed (`npm i hbs`). ```typescript I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), }, viewEngine: 'hbs' }) ``` -------------------------------- ### Configure I18nModule Asynchronously with Resolvers Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/quick-start.mdx Use `forRootAsync` to configure the I18nModule asynchronously, allowing dependency injection. This example includes Query, Header, Cookie, and Accept-Language resolvers, and uses a factory function to provide configuration. ```typescript import { Module } from '@nestjs/common'; import path from 'path'; import { AcceptLanguageResolver, QueryResolver, HeaderResolver, CookieResolver, I18nJsonLoader, I18nModule, } from 'nestjs-i18n'; @Module({ imports: [ I18nModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ fallbackLanguage: "en", loaderOptions: { path: path.join(__dirname, "/i18n/"), watch: true, }, }), resolvers: [ new QueryResolver(["lang", "l"]), new HeaderResolver(["x-custom-lang"]), new CookieResolver(), AcceptLanguageResolver, ], inject: [ConfigService], }), ], controllers: [], }) ``` -------------------------------- ### Configure Nunjucks with Fastify Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/nunjucks.md Configure Nunjucks for Fastify applications by specifying the engine, template directory, and view extension within the NestJS application setup. ```typescript import { join } from 'path'; async function bootstrap() { const app = await NestFactory.create( AppModule, new FastifyAdapter(), ); app.setViewEngine({ engine: { nunjucks: require('nunjucks'), }, templates: join(__dirname, '..', 'views'), viewExt: 'njk', }); await app.listen(3000); } ``` -------------------------------- ### Configure Resolvers in AppModule Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/concepts/resolver.md Configure the `nestjs-i18n` module with various built-in resolvers. This example shows how to set a fallback language, specify the path for translation files, and define custom resolvers for query parameters, headers, cookies, and accept-language. ```typescript I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), }, resolvers: [ new QueryResolver(['lang', 'l']), new HeaderResolver(['x-custom-lang']), new CookieResolver(), AcceptLanguageResolver, ], }) ``` -------------------------------- ### NestJS i18n Module Setup for Nunjucks Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/view_engines/nunjucks.md Configure the `nestjs-i18n` module to use Nunjucks as the view engine by setting `viewEngine: 'nunjucks'` and specifying the loader path. ```typescript I18nModule.forRoot({ fallbackLanguage: 'en', loaderOptions: { path: path.join(__dirname, '/i18n/'), }, viewEngine: 'nunjucks', }), ``` -------------------------------- ### Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nService.md Initializes a new instance of the I18nService. ```APIDOC ## Constructor ### Signature ```typescript new I18nService(i18nOptions, translations, supportedLanguages, logger, loaders, languagesSubject, translationsSubject): I18nService ``` ### Parameters - **i18nOptions** (`I18nOptions`): Configuration options for i18n. - **translations** (`Observable`): An observable stream of translations. - **supportedLanguages** (`Observable`): An observable stream of supported languages. - **logger** (`Logger`): The logger instance. - **loaders** (`I18nLoader[]`): An array of i18n loaders. - **languagesSubject** (`BehaviorSubject`): Subject for managing supported languages. - **translationsSubject** (`BehaviorSubject`): Subject for managing translations. ### Returns - `I18nService`: An instance of the I18nService. ``` -------------------------------- ### create() Static Method Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md Creates an I18nContext instance synchronously. ```APIDOC ### create() > `static` **create**(`ctx`, `next`): `void` #### Parameters ##### ctx `I18nContext` ##### next (...`args`) => `void` #### Returns `void` ``` -------------------------------- ### Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nContext.md Initializes a new instance of the I18nContext class. ```APIDOC ## Constructor > **new I18nContext**<`K`>(`lang`, `service`, `messageFormat`): `I18nContext` <`K`> #### Parameters ##### lang `string` ##### service [`I18nService`](I18nService.md)<`K`> ##### messageFormat `I18nMessageFormat` #### Returns `I18nContext` <`K`> ``` -------------------------------- ### Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nYamlLoader.md Initializes a new instance of the I18nYamlLoader class. ```APIDOC ## Constructor > **new I18nYamlLoader**(`options`): `I18nYamlLoader` ### Parameters #### options - **options** (`I18nAbstractLoaderOptions`) ### Returns - `I18nYamlLoader` ``` -------------------------------- ### Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/GrpcMetadataResolver.md Initializes a new instance of the GrpcMetadataResolver class. ```APIDOC ## Constructor > **new GrpcMetadataResolver**(`keys?`): `GrpcMetadataResolver` #### Parameters ##### keys? `string`[] = `...` #### Returns `GrpcMetadataResolver` ``` -------------------------------- ### I18nMiddleware Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nMiddleware.md Initializes the I18nMiddleware with necessary options, resolvers, service, message format, and module reference. ```APIDOC ## Constructor > **new I18nMiddleware**(`i18nOptions`, `i18nResolvers`, `i18nService`, `messageFormat`, `moduleRef`): `I18nMiddleware` #### Parameters ##### i18nOptions [`I18nOptions`](../interfaces/I18nOptions.md) ##### i18nResolvers [`I18nOptionResolver`](../type-aliases/I18nOptionResolver.md)[] ##### i18nService [`I18nService`](I18nService.md) ##### messageFormat `I18nMessageFormat` ##### moduleRef `ModuleRef` #### Returns `I18nMiddleware` ``` -------------------------------- ### Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/I18nAbstractLoader.md Initializes a new instance of the I18nAbstractLoader class. ```APIDOC ## Constructor > **new I18nAbstractLoader**(`options`): `I18nAbstractLoader` #### Parameters ##### options [`I18nAbstractLoaderOptions`](../interfaces/I18nAbstractLoaderOptions.md) #### Returns `I18nAbstractLoader` ``` -------------------------------- ### Using Plurals with `count` Argument in Ukrainian TypeScript Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/plurals.md Shows how to use the `i18n.t` function with different `count` values to get the correct Ukrainian plural forms. ```typescript await i18n.t('test.day_interval', { args: { count: 1 } }); // => 1 день await i18n.t('test.day_interval', { args: { count: 2 } }); // => 2 дні await i18n.t('test.day_interval', { args: { count: 5 } }); // => 5 днів await i18n.t('test.day_interval', { args: { count: 1.5 } }); // => 1.5 дня ``` -------------------------------- ### AcceptLanguageResolver Constructor Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/api/classes/AcceptLanguageResolver.md Initializes a new instance of the AcceptLanguageResolver class. It accepts optional configuration options. ```APIDOC ## Constructor > **new AcceptLanguageResolver**(`options?`): `AcceptLanguageResolver` ### Parameters #### options? - `options?` (`AcceptLanguageResolverOptions`): Optional configuration options for the resolver. ### Returns - `AcceptLanguageResolver`: An instance of the AcceptLanguageResolver. ``` -------------------------------- ### Access I18nContext in Exception Filter Source: https://github.com/toonvanstrijp/nestjs-i18n/blob/main/docs/guides/exception-filters.md Use `I18nContext.current()` to get the current translation context within an exception filter. This allows you to access the current language and perform translations. ```typescript import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from "@nestjs/common"; import { I18nContext } from "nestjs-i18n"; @Catch() export class TestExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const i18n = I18nContext.current(host); const response = host.switchToHttp().getResponse(); 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) ```