mongoose-translation-plugin
v2.0.0
Published
Auto-translation plugin for mongoose models
Downloads
37
Readme
Mongoose Translation Plugin
This translation plugin is designed for Mongoose together with a translation provider such as Google Translate or DeepL.
It is a simple plugin that allows you to translate your Mongoose models by simply adding translatable to any attribute
of a mongoose Schema and store overrides making contents searchable in any translated language.
How it works
The plugin will automatically create a new attribute translation for the translations and will handle the translation
of the attributes of the schema that have been flagged.
The translations are stored within each document in the translation attribute.
If a translation is not found for a given locale, the plugin allows you to retrieve the translation from the original document to that locale by requesting a translation provider
The translations provided can be overridden by the user.
A sourceUpdatedAt timestamp is set on the document whenever a translatable field changes.
If the timestamp is newer than the one stored on an existing auto-translation, the plugin will
automatically re-fetch that translation from the provider on the next translate() call.
Installation
> npm install mongoose-translation-pluginMongoose Translation Plugin does not require mongoose dependencies directly but expects you
to have the dependency installed.
Usage
The plugin is installed directly on the schema you want to translate. The Schema attributes that you want to translate should be flagged with translatable as shown below.
Prerequisites
The plugin require a translation provider to be passed as an argument. The translation provider must be an implementaiton of the TranslationProvider abstract class.
The TranslationProvider abstract class lets you implement your own translation provider, by implementing the getTranslations method as follows:
public getTranslations: TranslatorFunction = async ({text, from, to}: TranslatablePayload) => Promise<string[]>;The translation params (of type TranslatablePayload) are as follows:
- from: The original locale string of the text supported by the translation provider
- to: The target locale string of the text supported by the translation provider
- text: The text to be translated, as an array of strings.
The function must preserve the order of the strings. A sanitizer function can be passed as an option to sanitize the text before sending it to the translation provider.
An example with Google Translate and DeepL is given in the repository.
Plugin Mongoose Schema
First you need to plugin into the schema you want translatable, and define the attributes you want translatable by adding translatable: true in the schema definition.
If the Schema contains nested objects, you can also define the nested object as translatable.
import { Schema } from 'mongoose';
import { type TranslatableDocument, type TranslatorFunction,translationPlugin, TranslationProvider } from 'mongoose-translation-plugin';
class MyTranslator extends TranslationProvider {
public getTranslations: TranslatorFunction = async (payload) => {
// implement your own translation provider here
}
}
interface ISimple {
translatableStringField: string;
nonTranslatableStringField: string;
other: number;
}
type ISimpleDocument = ISimple & TranslatableDocument<ISimple>;
const schema = new Schema({
translatableStringField: { type: String, translatable: true },
nonTranslatableStringField: String,
other: Number
});
schema.plugin(translationPlugin, { provider: TranslationProvider.getInstance(MyTranslator) });
export const SimpleModel = mongoose.model<ISimpleDocument>('SimpleModel', schema);You're free to define your model how you like. Mongoose Translation Plugin will add :
- a
languageattribute (can be renamed with thelanguageFieldoption) - a
sourceUpdatedAtattribute (Date, not configurable) tracking when translatable fields last changed - a
translationattribute that contains all the translations - a
translatemethod to retrieve the document in a specific language as plain object - a
updateOrReplaceTranslationmethod to manually manage the translation of a locale.
Additionally, Mongoose Translation Plugin adds some other utility methods to your Schema. See the API Documentation section for more details.
Options
The plugin accepts an options object as a second argument. The options are as follows:
languageField(default:'language'): The name of the attribute that stores the document language.- ~~
translationField(default:'translation'): The name of the attribute that contains the translations.~~ (To be implemented) translator: The translation function (deprecated — useproviderinstead).sanitizer: A function called to sanitize text before sending it to the translation provider.
Translation
The plugin will automatically translate the translatable fields of the document when the function translate is called.
Nested objects are also supported.
const document = await SimpleModel.create({ translatableStringField: 'Hello', nonTranslatableStringField: 'World', other: 42 });
const documentTranslation = await document.translate('fr');Output
The documentTranslation is a plain object as follows:
{
"nativeLanguage": "en",
"supportedLanguages": ["en", "fr"],
"language": "fr",
"sourceUpdatedAt": "<ISO timestamp of the last translatable-field change>",
"autoTranslated": true,
"translatableStringField": "Bonjour",
"nonTranslatableStringField": "World",
"other": 42
}Override an Automatic Translation
This feature is not implemented yet in the plugin, but as a workaround, it can be done manually
by calling the updateOrReplaceTranslation method, and ensuring that autoTranslate is set to false.
Limitations
The plugin does not support populated fields, and will not translate the populated fields of the document. The models we had implemented so far did not require this feature, as they where pretty simple, and could be combined separately, but it could be implemented in the future.
Contribute
Please respect the Code of Conduct to submit your improvement change requests.
License
Mongoose Translation Plugin is licensed under the AGPL license.
