DigiComp.FlowTranslationEnd.../Resources/Private/JavaScriptModules/flow-translation-endpoint/translate.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

// storage for promises with the same ids so the same request is not issued twice
const translations = {};
export function translateIdPatterns(idPatterns)
{
if (!translations[idPatterns.join(',')]) {
translations[idPatterns.join(',')] = getJSON(idPatterns);
}
return translations[idPatterns.join(',')];
}
export function arrayFromPaths(units)
{
const result = {};
for (const [key, value] of Object.entries(units)) {
let cur = result;
const parts = key.split('.'),
lastPart = parts.pop();
parts.forEach(function(elem){
cur[elem] = cur[elem] || {};
cur = cur[elem];
});
cur[lastPart] = value;
}
return result;
}
async function getJSON(idPatterns)
{
const uri = new URL(document.documentElement.dataset.xliffUri, document.location);
uri.searchParams.set(document.documentElement.dataset.xliffParameter, idPatterns);
const response = await fetch(uri, {headers: {
'Accept': 'application/json',
'Accept-Language': document.documentElement.lang,
}});
if (!response.ok) {
return Promise.reject('Unexpected server response');
}
return await response.json();
}