Add 'uploadJson' method

master
KaKi87 2022-03-27 20:49:14 +02:00
parent 1c17ba142f
commit 6a78eee9f1
1 changed files with 55 additions and 16 deletions

71
mod.js
View File

@ -12,7 +12,7 @@ module.exports = ({
apiKey
}) => {
const client = axios.create({
baseURL: `${apiUrl}/api`
baseURL: apiUrl
});
client.interceptors.request.use(config => ({
...config,
@ -21,27 +21,66 @@ module.exports = ({
'ak': apiKey
}
}));
/**
* Download project i18n data as JSON objects
* @returns {Promise}
*/
const downloadJson = async () => {
const
{
data
} = await client.get(
'api/project/export/jsonZip',
{
responseType: 'arraybuffer'
}
),
zip = JSZip(),
result = {};
await zip.loadAsync(data);
for(const file of Object.values(zip.files))
result[file.name.split('.')[0]] = JSON.parse(await file.async('string'));
return result;
};
return {
downloadJson,
/**
* Download project i18n data as JSON objects
*
* @param {object} json
* @param {function} [onProgress]
* @returns {Promise}
*/
downloadJson: async () => {
uploadJson: async (
json,
{
onProgress
} = {}) => {
const
{
data
} = await client.get(
'project/export/jsonZip',
{
responseType: 'arraybuffer'
remoteJson = await downloadJson(),
data = [];
for(const [locale, localeJson] of Object.entries(json)){
for(const [key, value] of Object.entries(localeJson)){
if(value !== remoteJson[locale]?.[key]){
let item = data.find(item => item['key'] === key);
if(!item){
item = {
key,
'translations': {}
};
data.push(item);
}
item['translations'][locale] = value;
}
),
zip = JSZip(),
result = {};
await zip.loadAsync(data);
for(const file of Object.values(zip.files))
result[file.name.split('.')[0]] = JSON.parse(await file.async('string'));
return result;
}
}
for(let i = 0; i < data.length; i++){
await client.post(
'v2/projects/translations',
data[i]
);
if(typeof onProgress === 'function')
onProgress({ index: i+1, count: data.length });
}
}
};
};