portfolio-valentin-le-moign/composables/useFetchTranslation.js

51 lines
1.6 KiB
JavaScript

export const useFetchTranslation = async (collection) => {
const i18n = useI18n();
try {
const translations = await $fetch(`/api/items/${collection}_translations`);
translations.data.forEach(value => {
let translationValues = {};
translationValues[collection] = {};
Object.entries(value).forEach(([k, v]) => {
if (k !== 'id' && k !== `${collection}_id`) {
if(hasDuplicateValueForKey(translations.data, 'languages_code')) {
const collectionIdKey = value[`${collection}_id`];
if (!translationValues[collection][collectionIdKey]) {
translationValues[collection][collectionIdKey] = {};
}
translationValues[collection][collectionIdKey][k] = v;
} else {
// singleton
translationValues[collection][k] = v;
}
}
});
i18n.mergeLocaleMessage(
value.languages_code.toLowerCase(),
translationValues
);
// console.log(i18n.getLocaleMessage(value.languages_code.toLowerCase()));
});
} catch (error) {
console.error('Error fetching translations:', error);
}
};
// check if collection is singleton or multiple items
function hasDuplicateValueForKey(array, key) {
const seenValues = new Set();
for (const obj of array) {
if (seenValues.has(obj[key])) {
return true;
}
seenValues.add(obj[key]);
}
return false;
}