your-gold/plugins/i18n.ts
2025-05-29 12:26:19 +02:00

32 lines
866 B
TypeScript

import type { VueI18n } from "vue-i18n";
import { usePB } from "~/composables/usePB";
export default defineNuxtPlugin(async (nuxtApp) => {
const loaded = [] as Array<string>;
const i18n = nuxtApp.$i18n as VueI18n;
const pb = usePB();
i18n.onBeforeLanguageSwitch = async (oldLocale, newLocale) => {
if (loaded.includes(newLocale)) return;
try {
const translation = await pb.collection("translation").getList(1, 1, {
expand: "id_lang",
filter: `id_lang.iso='${newLocale}'`,
});
if (translation.totalItems === 1) {
i18n.setLocaleMessage(newLocale, translation.items[0].data);
} else {
i18n.setLocaleMessage(newLocale, {});
}
loaded.push(newLocale);
} catch (err) {
console.error("❌ Failed to load translation for locale:", newLocale);
throw err;
}
};
});