mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
feat: wrap up translation logic
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user