-
Notifications
You must be signed in to change notification settings - Fork 34
/
importFromCsv.ts
82 lines (71 loc) · 2.24 KB
/
importFromCsv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {mergeDeepLeft, uniq} from 'ramda';
import {unflatten} from 'safe-flat';
import * as csv from '@fast-csv/parse';
import {getContentByType} from './src/utils/utils';
import {DEFAULT_LANGUAGE_TAG, LANGUAGE_TAG} from '../shared/src/i18n/constants';
import fs from 'fs';
import path from 'path';
const FROM_LANGUAGE_TAG = DEFAULT_LANGUAGE_TAG;
const [, , TO_LANGUAGE_TAG, CSV_FILE] = process.argv;
if (!TO_LANGUAGE_TAG) {
throw new Error('Missing language argument');
}
if (!CSV_FILE) {
throw new Error('Missing csv file argument');
}
const skipLanguageMergeForTypes = ['email', 'ui'];
type Translation = {
Type: string;
File: string;
Key: string;
} & {
[key in LANGUAGE_TAG]: string;
};
async function readFileCsvFile(filePath: string): Promise<Translation[]> {
return new Promise((resolve, reject) => {
const data: Translation[] = [];
csv
.parseFile(filePath, {headers: true})
.on('error', reject)
.on('data', row => data.push(row))
.on('end', () => resolve(data));
});
}
const main = async () => {
const data = await readFileCsvFile(CSV_FILE);
const types = uniq(data.map(({Type}) => Type));
types.forEach(type => {
const typeContent = getContentByType(type);
const typeTranslations = data.filter(({Type}) => Type === type);
const files = uniq(typeTranslations.map(({File}) => File));
files.forEach(fileKey => {
const content = typeContent[fileKey];
const fileTranslations = typeTranslations
.filter(
({File, ...translations}) =>
File === fileKey && translations[TO_LANGUAGE_TAG],
)
.reduce(
(acc, {Key, ...translations}) => ({
...acc,
[Key]: translations[TO_LANGUAGE_TAG],
}),
{},
);
if (Object.keys(fileTranslations).length) {
const filePath = path.resolve('src', type, `${fileKey}.json`);
const fileContent = {
...content,
[TO_LANGUAGE_TAG]: mergeDeepLeft(
unflatten(fileTranslations),
skipLanguageMergeForTypes.includes(type)
? {}
: content[FROM_LANGUAGE_TAG],
),
};
fs.writeFileSync(filePath, JSON.stringify(fileContent, null, 2));
}
});
});
};
main();