TranslateTransform
This file defines the TranslateTransform
function, which is used to automatically translate strings or objects containing translation tags in responses. It is designed for use in the @sodacore/core
i18n (internationalization) system, enabling dynamic translation of content based on the user's accepted languages.
Features
- Automatic Translation: Scans strings and objects for translation tags (e.g.,
_t(key)
) and replaces them with the appropriate translation. - Recursive Object Support: Recursively traverses objects and arrays, translating all string values containing translation tags.
- Language Negotiation: Determines the best language to use based on the
accept-language
header from the request. - Integration with I18nProvider: Uses the registered
I18nProvider
to perform translations and language negotiation.
Usage
This transform is typically used in response pipelines or controllers to ensure all translatable content is localized before being sent to the client.
typescript
import TranslateTransform from './transform/translate';
const localizedResponse = TranslateTransform(context, response);
API
TranslateTransform(context: any, response: any): any
- context: The request context, expected to provide access to request headers.
- response: The response data to be translated (can be a string, object, or array).
- Returns: The translated response, with all translation tags replaced by their localized values.
How It Works
- Language Detection: Retrieves the
accept-language
header from the request to determine the user's preferred languages. - Translation Tag Matching: Uses regex patterns to find all occurrences of
_t(key)
in strings. - Translation: For each match, uses the
I18nProvider
to translate the key into the best available language. - Recursive Transformation: If the response is an object or array, recursively traverses all properties and elements, translating any strings found.
- Return Value: Returns the fully translated response.
Notes
- Translation tags must be in the format
_t(key)
to be recognized and replaced. - If no suitable translation is found, the original key is used as a fallback.
- The function does not mutate the original response if it is a string, but does mutate objects and arrays in place.
- Designed to be used as a transform in the Sodacore i18n system.