Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mololab
GitHub Repository: mololab/json-translator
Path: blob/master/src/core/json_file.ts
235 views
1
import { translatedObject } from '..';
2
import { error, messages, success } from '../utils/console';
3
import { getFile, getRootFolder, saveFilePublic } from './core';
4
import { objectTranslator } from './json_object';
5
import { matchYamlExt } from '../utils/yaml';
6
import { TranslationConfig } from '../modules/modules';
7
import { getLanguageKeyFromValue } from '../modules/helpers';
8
9
export async function fileTranslator(
10
TranslationConfig: TranslationConfig,
11
tempObjectPath: string,
12
from: string,
13
to: string[],
14
newFileName: string
15
) {
16
// step: get file details -> data, path
17
let { jsonObj, objectPath } = await getFileFromPath(tempObjectPath);
18
if (jsonObj === undefined) {
19
error(messages.file.no_file_in_path);
20
return;
21
}
22
23
jsonObj = { data: JSON.parse(jsonObj) };
24
25
// step: check if translation file already exists, if exists save content of it in oldTranslations
26
let oldTranslations = JSON.parse("{}")
27
let latestPath = objectPath.replace(/\\/g, '/');
28
const fileExt = getFileExt(latestPath);
29
let rootFolder = getRootFolder(latestPath);
30
31
for (const lang of to) {
32
// Filename of tranlated file
33
let baseFileName = newFileName
34
? `${newFileName}.${lang}.${fileExt}`
35
: `${lang}.${fileExt}`;
36
37
// Construct full path using rootFolder
38
let fileName = `${rootFolder}/${baseFileName}`;
39
40
let response = await getFileFromPath(fileName);
41
let oldTranslation = response?.jsonObj
42
try{
43
if (oldTranslation === undefined) {
44
// Old Translation not found
45
console.log(`📋 Cache miss: No existing translation found for ${lang} in ${fileName}`);
46
oldTranslations[lang] = { data: {} };
47
} else {
48
oldTranslation = { data: JSON.parse(oldTranslation) };
49
oldTranslations[lang] = oldTranslation;
50
console.log(`📋 Cache hit: Found existing translation for ${lang} in ${fileName}`);
51
}
52
} catch{
53
// If error in parsing json skip it
54
console.log(`⚠️ Error parsing translation file for ${lang} in ${fileName}`);
55
oldTranslations[lang] = { data: {} };
56
}
57
58
}
59
60
// step: translate object
61
let newJsonObj = await objectTranslator(TranslationConfig, jsonObj, from, to, oldTranslations);
62
if (newJsonObj === undefined) {
63
error(messages.file.cannot_translate);
64
return;
65
}
66
67
// step: save translated data
68
(newJsonObj as Array<translatedObject>).forEach(async (element, index) => {
69
const currentJsonObj = element.data;
70
71
let fileName = newFileName
72
? `/${newFileName}.${to[index]}.${fileExt}`
73
: `/${to[index]}.${fileExt}`;
74
75
await saveFilePublic(rootFolder + fileName, currentJsonObj);
76
77
success(
78
`For ${getLanguageKeyFromValue(
79
to[index],
80
TranslationConfig.TranslationModule.languages
81
)} --> ${fileName} created.`
82
);
83
});
84
}
85
86
export async function getFileFromPath(
87
objectPath: string
88
): Promise<{ jsonObj: any; objectPath: string }> {
89
let jsonObj: any = await getFile(objectPath);
90
91
if (jsonObj === undefined) {
92
objectPath = __dirname + '\\' + objectPath;
93
94
jsonObj = await getFile(objectPath);
95
}
96
97
return { jsonObj, objectPath };
98
}
99
100
function getFileExt(latestPath: string): string {
101
// Check if source file has YAML extension and return the extension ("yml" or "yaml").
102
const sourceFileMatchYamlExt = matchYamlExt(latestPath);
103
104
// When source file has "yml" or "yaml" extension, use the same in output file path.
105
// Otherwise, default "json" extension used.
106
const fileExt = sourceFileMatchYamlExt || 'json';
107
108
return fileExt;
109
}
110
111