feat: wrap up translation logic

This commit is contained in:
Mohamed Marrouchi
2024-09-24 11:23:40 +01:00
parent 16e7431d83
commit ecb8d9745a
35 changed files with 291 additions and 260 deletions

View File

@@ -8,7 +8,6 @@
*/
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import {
I18nService as NativeI18nService,
Path,
@@ -24,11 +23,7 @@ import { Translation } from '@/i18n/schemas/translation.schema';
export class I18nService<
K = Record<string, unknown>,
> extends NativeI18nService<K> {
private dynamicTranslations: Record<string, Record<string, string>> =
config.chatbot.lang.available.reduce(
(acc, curr) => ({ ...acc, [curr]: {} }),
{},
);
private dynamicTranslations: Record<string, Record<string, string>> = {};
t<P extends Path<K> = any, R = PathValue<K, P>>(
key: P,
@@ -40,17 +35,19 @@ export class I18nService<
...options,
};
let { lang } = options;
lang = lang ?? this.i18nOptions.fallbackLanguage;
lang = this.resolveLanguage(lang);
// Translate block message, button text, ...
if (lang in this.dynamicTranslations) {
if (key in this.dynamicTranslations[lang]) {
return this.dynamicTranslations[lang][key] as IfAnyOrNever<
R,
string,
R
>;
if (this.dynamicTranslations[lang][key]) {
return this.dynamicTranslations[lang][key] as IfAnyOrNever<
R,
string,
R
>;
}
return options.defaultValue as IfAnyOrNever<R, string, R>;
}
}
@@ -59,15 +56,13 @@ export class I18nService<
return super.t<P, R>(key, options);
}
@OnEvent('hook:i18n:refresh')
initDynamicTranslations(translations: Translation[]) {
refreshDynamicTranslations(translations: Translation[]) {
this.dynamicTranslations = translations.reduce((acc, curr) => {
const { str, translations } = curr;
Object.entries(translations)
.filter(([lang]) => lang in acc)
.forEach(([lang, t]) => {
acc[lang][str] = t;
});
Object.entries(translations).forEach(([lang, t]) => {
acc[lang] = acc[lang] || {};
acc[lang][str] = t;
});
return acc;
}, this.dynamicTranslations);

View File

@@ -33,7 +33,7 @@ export class TranslationService extends BaseService<Translation> {
public async resetI18nTranslations() {
const translations = await this.findAll();
this.i18n.initDynamicTranslations(translations);
this.i18n.refreshDynamicTranslations(translations);
}
/**