Localization

Localizable

The Localizable system provides internationalization (i18n) support for multi-language content in NestJS applications. The utilies system is built on the premise that the translations is stored on a different table/model, and in the run-time all translations for all languages are fetched from the storage then, only the user prefered language is populated within the response

Overview

  • @LocalizableOptions - Class-level decorator for localization configuration

  • @Localizable - Property-level decorator for translatable fields

  • setupLocalizable - Global configuration function

Setup

1. Global Configuration

In your main.ts file call setupLocalizable to setup the localization process, you need to provide 2 options

  • translate: a function that takes a token and return its translation, depending on the user preference

    translate(token: string): string;
  • getCurrentLocale a function that provides the current language of the user

    getCurrentLocale(): string;
// main.ts
import { setupLocalizable } from '@tradinos/cms-backend-entity';

setupLocalizable({
  translate: (token) => app.get<I18nService>(I18nService).translate(token),
  getCurrentLocale: () => I18nContext.current()?.lang ?? 'en',
});

2. DTO Configuration

LocalizableOptions

Class-level decorator to configure localization:

In addition to the localizations key, LocalizableOptions takes 2 optional argument

  • factory an optional function that taesk key, translations, and locale and return the translations of the key to the locale extracted from the translations object. If not provided a default implementation will be used which assumes the translations is an array of objects each containing translations of all keys and a locale key

  • localeKey this parameter is useful only when the default factory is used, it determines the key within the translations object that contains the locale. By default the key name that will be used is locale

Localizable

Property-level decorator for translatable fields:

How It Works

  1. System detects current locale from request context

  2. For @Localizable() fields, finds matching translation in translations array

  3. Automatically populates fields with translated content

  4. Falls back to original value if translation not found

Last updated