Skip to content

I18nProvider

This file defines the I18nProvider class, a provider for translation and language negotiation in the @sodacore/core i18n (internationalization) system. It offers methods to translate strings, handle fallbacks, and determine the best matching language based on user preferences and available translations.


Features

  • Translation Methods: Provides methods to translate keys using the current language or a specified fallback.
  • Language Negotiation: Determines the best matching language from an Accept-Language header or similar input.
  • Integration with I18nService: Uses the injected I18nService for translation logic and available language management.
  • Dependency Injection: Uses @Provide and @Inject decorators for DI integration.

Usage

typescript
import I18nProvider from './provider/i18n';

const i18n = new I18nProvider();

// Translate a key for a specific language
const greeting = i18n.t('greeting.hello', 'en-US');

// Translate with a fallback value
const result = i18n.translate('missing.key', 'fr-FR', 'Default Value');

// Determine the best available language from an Accept-Language header
const bestLang = i18n.getAvailableTranslation('fr-FR,fr;q=0.8,en-US;q=0.6');

API

Methods

t(query: string, languageCode: string): string

Translates the given key using the specified language code. Returns the key itself if no translations are available.

translate(query: string, languageCode: string, fallback?: string): string

Translates the given key using the specified language code, or returns the fallback (or key) if not available.

getAvailableTranslation(acceptedLanguages: string): string | null

Determines the best matching language code from a comma-separated list (e.g., from an Accept-Language header), considering available translations and language priorities. Returns null if no suitable match is found.


How It Works

  1. Translation:

    • Checks if translations are loaded via I18nService.
    • Uses I18nService.translate to perform the actual translation.
    • Falls back to the provided fallback value or the original key if no translation is found.
  2. Language Negotiation:

    • Parses the accepted languages string into an array of language codes and priorities.
    • Compares against available languages from I18nService.
    • Selects the best match based on priority and availability, considering the default language if set.

Notes

  • Designed to be used as a provider within the Sodacore dependency injection system.
  • Relies on I18nService for translation data and available languages.
  • Handles both direct translation and language negotiation for HTTP or API scenarios.

Released under the Apache-2.0 License.