Skip to content

TranslateTransform

This file defines the TranslateTransform function, a response transformer for the @sodacore/core i18n (internationalization) module. It automatically translates HTTP responses based on the client's Accept-Language header, using the available translations provided by the I18nProvider.


Features

  • Automatic Response Translation: Transforms response data (strings or objects) into the best-matching language based on the request's Accept-Language header.
  • Integration with I18nProvider: Uses the registered I18nProvider to perform translation and language negotiation.
  • Non-intrusive: Returns the original response if no suitable translation is available or if the response is not a string or object.

Usage

This transformer is typically registered in the Sodacore HTTP pipeline to automatically localize responses:

typescript
import TranslateTransform from './transform/translate';

app.useResponseTransform(TranslateTransform);

API

TranslateTransform(context: any, response: any): any

  • context: The HTTP context, expected to provide access to the request and headers.
  • response: The response data to be translated (string or object).

Returns:

  • The translated response if a suitable language is found and the response is a string or object.
  • The original response otherwise.

How It Works

  1. Language Detection: Retrieves the accept-language header from the request to determine the client's preferred languages.
  2. Language Negotiation: Uses I18nProvider.getAvailableTranslation to select the best available language code.
  3. Translation: If a suitable language is found and the response is a string or object, calls I18nProvider.autoTranslate to translate the response.
  4. Fallback: If no translation is possible, returns the original response unchanged.

Notes

  • This transformer relies on the I18nProvider being registered in the Sodacore registry.
  • Only responses that are strings or objects are considered for translation.
  • Designed for use in HTTP APIs where automatic localization of responses is desired.

Released under the Apache-2.0 License.